字符串替换Python中的元音?

new*_*bie 3 python

预期:

>>> removeVowels('apple')
"ppl"
>>> removeVowels('Apple')
"ppl"
>>> removeVowels('Banana')
'Bnn'
Run Code Online (Sandbox Code Playgroud)

代码(初学者):

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

我如何小写和大写?

agf*_*agf 6

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

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
Run Code Online (Sandbox Code Playgroud)

你也可以把它写成

''.join(char for char in word if char.lower() not in 'aeiou')
Run Code Online (Sandbox Code Playgroud)

除了一次找到一个非元音join需要它们制作新字符串,而不是将它们添加到列表然后在最后加入它们之外,它做同样的事情.

如果你想加快它的速度,那么创建值的字符串set可以更快地查找其中的每个字符,并且使用大写字母也意味着您不必将每个字符转换为小写.

''.join(char for char in word if char not in set('aeiouAEIOU'))
Run Code Online (Sandbox Code Playgroud)

  • 加快使用[bytes.translate()](http://stackoverflow.com/questions/7301292/string-replace-vowels-in-python/7301382#7301382). (2认同)

jfs*_*jfs 6

使用bytes.translate()方法:

def removeVowels(word, vowels=b'aeiouAEIOU'):
    return word.translate(None, vowels)
Run Code Online (Sandbox Code Playgroud)

例:

>>> removeVowels('apple')
'ppl'
>>> removeVowels('Apple')
'ppl'
>>> removeVowels('Banana')
'Bnn'
Run Code Online (Sandbox Code Playgroud)


JBe*_*rdo 5

re.sub('[aeiou]', '', 'Banana', flags=re.I)
Run Code Online (Sandbox Code Playgroud)