Python元音卸妆

时间:2016-05-23 20:09:50

标签: python

我为Codecademy编写了一个程序,用于从字符串中删除元音。由于某些我无法弄清楚的原因,它无法正常工作。这是我的代码:

def anti_vowel(text):
    wordcontents=list(text)
    vowel=['a','e','i','o','u']
    for letter in wordcontents:
        if letter in vowel:
            wordcontents.remove(letter)
    word=''
    word=word.join(wordcontents)
    return word

anti_vowel("Hey Look Words!")

结果:

"Hy lk Words!"

有什么见解?我的错是什么?

2 个答案:

答案 0 :(得分:2)

def anti_vowel(text):
    vowel= 'aeiou'
    return ''.join(c for c in text if c not in vowel)

答案 1 :(得分:0)

Alex Hall的评论是正确的。

正在发生的事情是你正在跳过第二个' o'在'看'然后当你在“单词”中找到它时将其删除。在删除项目时迭代字符串的方式会导致您跳过字母,直到您连续两个元音都没有问题。

在你的for循环后面放一个打印语句,看看我的意思

print "checking " + letter + " in " + ''.join(wordcontents):

解决问题的更好方法是迭代元音列表并继续从字符串中删除元音,直到元音不再出现在字符串中。

remove遍历列表并删除提供的对象的第一个实例。

[ 1, 2, 3, 1].remove(1) #this removes just the first instance of 1

如果再次拨打列表中的删除(1),它将删除最后一个号码。

如果再次调用它会引发异常。

如果你这样做

while 'a' in wordcontents:
    wordcontents.remove('a')

它将继续调用remove函数,直到列表中没有更多实例。