【发布时间】:2015-10-03 11:25:49
【问题描述】:
我正在尝试编写一些程序来过滤掉一串文本中的所有元音,但我不确定为什么我的函数不起作用。这是我的代码
def anti_vowel(text):
letters = text.split() #make a list of all the letters in the string
index = 0 #for del
for x in letters:
if x == "a" or x == "A" or x == "u" or x == "U" or x == "i" or x == "I" or x == "o" or x == "O" or x == "e" or x == "E":
del letters[index]
index += 1 #to make the if-clause work
return "".join(letters) #turn the edited list into a string
在遍历字母时,如果字母中的对象是元音,则应该激活 if 子句,对吧?所以它应该删除那个对象。但是我做错了什么?
【问题讨论】:
-
您不应该在迭代列表时更改它。
-
您正在使用
del letters[index]。列表越来越小,当您执行index += 1时,您实际上是在跳过一个元素(由于删除而被移动)。