python remove()函数不工作

2024-05-15 09:22:33 发布

您现在位置:Python中文网/ 问答频道 /正文

学习Python,由于某些原因我不能让Python remove函数工作。当我在控制台中用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)

Tags: 函数脚本列表input原因removelistword
1条回答
网友
1楼 · 发布于 2024-05-15 09:22:33

这里有:

word_input = list(word_input)

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

^{2}$

也就是说,另一个字符串列表。在

你需要:

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只删除元素的第一个出现,因此您可能需要反复调用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)

相关问题 更多 >