从字符串中删除元音

时间:2014-04-19 21:52:15

标签: python python-2.7

我试图在标题中尽可能清楚,但有点难以解释。我必须从某个字符串中删除所有元音;为此,我创建了一个循环,遍历由该字符串的字符组成的列表,删除元音然后加入它们:

def anti_vowel(text):
    vow = ["a", "e", "i", "o", "u"]
    chars = []

    for i in text:
        chars.append(i)

    for i in chars:
        if i.lower() in vow:
            chars.remove(i)

    return "".join(chars)

问题在于,当我运行代码时,总会有一个不会被删除的元音。例子:

>>> anti_vowel("Hey look Words!")
Hy lk Words!

>>> anti_vowel("Frustration is real")
Frstrton s ral

我绝不是Python的专家,但这很令人困惑。为什么它会删除一些字母并保留其他字母,即使它们完全相同?

3 个答案:

答案 0 :(得分:5)

来自@arshajii的评论解释了为什么删除循环中的字符不是一个好主意。 要解决你的代码中的问题,(请注意,有更有效的方法来实现这一点,但看起来你正在学习,所以我将把它留在这里。)

def anti_vowel(text):
    vow = ["a", "e", "i", "o", "u"]
    chars = []

    for i in text: #No need of the two separate loops
        if i.lower() not in vow:
            chars.append(i)

    return "".join(chars)

演示:

>>> def anti_vowel(text):
...     vow = ["a", "e", "i", "o", "u"]
...     chars = []
...     for i in text: #No need of the two separate loops
...         if i.lower() not in vow:
...             chars.append(i)
...     return "".join(chars)
... 
>>> anti_vowel("Hey look Words!")
'Hy lk Wrds!'
>>> anti_vowel("Frustration is real") 
'Frstrtn s rl'
>>> 

答案 1 :(得分:4)

如果你的目标是返回一个字符串,该字符串与删除元音的原始字符串相同,请尝试:

import re
def anti_vowel(text):
    return re.sub("[aeiou]+", "", text)

答案 2 :(得分:3)

这是一种有效的方式:

mytext = 'hello world!'
vowels = ['a', 'e', 'i', 'o', 'u']
result = ''
for letter in mytext:
    if letter not in vowels:
        result += letter

print(result)