python remove() 函数不工作

python remove() function not working

正在学习 Python,但出于某种原因,我无法使用 python 删除功能。当我在控制台的 Python 中以交互方式测试它时它起作用,但当我编写脚本时它不起作用。请帮帮我!它将输入变成一个列表但不删除元音。

print("\nVowel Removal")
print("Enter a word to have the vowel removed.")
word_input = input("> ")
word_input = list(word_input)

vowels = list('aeiou')
output = []

while True:
    try:
        word_input.remove(vowels)
    except:
        print("You must enter a word.")
        break

print(word_input)

这里有:

word_input = list(word_input)

所以 word_input 是一个字符串列表(特别是字符)。 vowels 是:

vowels = list('aeiou')

即另一个字符串列表。

你做到了:

word_input.remove(vowels)

总是失败,因为 vowels 是一个字符串列表,而 word_input 只包含字符串。 remove 删除 单个元素 。它不会 删除参数中包含的所有元素。 查看错误信息:

In [1]: vowels = list('aeiou')

In [2]: vowels.remove(vowels)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-2-6dd10b35de83> in <module>()
----> 1 vowels.remove(vowels)

ValueError: list.remove(x): x not in list

请注意它说:list.remove(x): x not in list 所以 remove 的参数应该是列表的一个元素,而不是要删除的元素列表。

你必须做的:

for vowel in vowels:
    word_input.remove(vowel)

删除所有元音。此外 remove 仅删除元素的 first 出现,因此您可能必须重复调用 remove 才能删除所有出现的元音。

注意:要从字符串中删除元音,您可以简单地使用:

the_string.translate(dict.fromkeys(map(ord, vowels)))

如:

In [1]: the_string = 'Here is some text with vowels'
   ...: vowels = 'aeiou'
   ...: 

In [2]: the_string.translate(dict.fromkeys(map(ord, vowels)))
Out[2]: 'Hr s sm txt wth vwls'

或者,如果您想使用这些列表:

result = []
# vowels = set('aeiou') may be faster than using a list
for char in word_input:
    if char not in vowels:
        result.append(char)