如何从列表中删除字母?

时间:2018-11-11 21:39:43

标签: python

我正在尝试制作一个程序,在其中接收用户输入并吐出不带字母的输入。我真的很困惑为什么这不起作用。

numText = input("Give me a list of characters: ") # Gets user input of characters
numList = list(numText) # Turns ^ into list

for char in numList: # Every character in the list
    if char.isalpha(): # Checks to see if the character is a letter
        numList.remove(char) # Removes the letter from the list

print(numList) # Prints the new list without letters
input("") # Used so the program doesnt shut off

我知道这真是愚蠢,所以抱歉问。

1 个答案:

答案 0 :(得分:6)

您不应同时进行迭代和删除,而应使用list comprehension

numText = input("Give me a list of characters: ") # Gets user input of characters

numList = [char for char in numText if not char.isalpha()]

print(numList) # Prints the new list without letters
input("")