import re
new_list = [re.sub("^the","", artist.lower()).replace("","") for artist in artist_list]
如果你认为列表推导中的表达式太大,最好直接使用for循环。
[artist.lower().replace('the , '').replace(' ','') for artist in artist_list]
或者,使用正则表达式,整个过程可能更简单,更灵活:
>>> re.sub(r'($the)|[ ]', '', 'The Artist Formerly Known As Prince')
'TheArtistFormerlyKnownAsPrince'
def cleanup(artist):
artist = artist.lower().replace(' ', '')
if artist.startswith('the'):
artist = artist[3:]
return artist
new_list = [cleanup(artist) for artist in artist_list]