小编典典

Python中的字符串替换元音?

python

预期:

>>> removeVowels('apple')
"ppl"
>>> removeVowels('Apple')
"ppl"
>>> removeVowels('Banana')
'Bnn'

代码(入门):

def removeVowels(word):
    vowels = ('a', 'e', 'i', 'o', 'u')
    for c in word:
        if c in vowels:
            res = word.replace(c,"")
    return res

如何同时使用小写和大写?


阅读 185

收藏
2021-01-16

共1个答案

小编典典

这是使用列表而不是生成器的版本:

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'))
2021-01-16