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]