这是使用列表而不是生成器的版本:
def removeVowels(word):
letters = [] # make an empty list to hold the non-vowels
for char in word: # for each character in the word
if char.lower() not in 'aeIoU': # if the letter is not a vowel
letters.append(char) # add it to the list of non-vowels
return ''.join(letters) # join the list of non-vowels together into a string
您也可以像
''.join(char for char in word if char.lower() not in 'aeIoU')
这样做的作用相同,只是一次join
需要找到一个非元音来制作新的字符串,而不是将它们添加到列表中然后在最后将它们连接起来。
如果您想加快速度,将值字符串设置为aset
可以更快地查找其中的每个字符,并且也具有大写字母意味着您不必将每个字符都转换为小写。
''.join(char for char in word if char not in set('aeIoUAEIoU'))