【问题标题】:Loop to remove characters from list not working [duplicate]循环从列表中删除字符不起作用[重复]
【发布时间】:2013-10-18 02:15:57
【问题描述】:

我有一个标点符号列表,我希望循环从用户输入的句子中删除它,它似乎连续忽略多个标点符号?

punctuation = ['(', ')', '?', ':', ';', ',', '.', '!', '/', '"', "'"]
usr_str=input('Type in a line of text: ')

#Convert to list
usr_list= list(usr_str)

#Checks if each item in list is punctuation, and removes ones that are
for char in usr_list:
    if char in punctuation:
        usr_list.remove(char)

#Prints resulting string
print(''.join(usr_list))

现在这适用于:

This is an example string, which works fine!

哪些打印:

This is an example string which works fine

但是,像这样:

Testing!!!!, )

给予:

Testing!!

提前感谢您的帮助!

【问题讨论】:

标签: python list for-loop python-3.x


【解决方案1】:

您正在更改列表您正在迭代它。绝不是一个好主意。

使其工作的一种方法是遍历列表的副本:

for char in usr_list[:]:  # this is the only part that changed; add [:] to make a copy
    if char in punctuation:
        usr_list.remove(char)

如果有更多经验,您可能会改用“列表推导式”:

usr_list = [char for char in usr_list if char not in punctuation]

您可能会使用filter() 或正则表达式或...得到其他答案。但一开始要保持简单:-)

另一种方法是制作两个不同的列表。假设您的输入列表是input_list。那么:

no_punc = []
for char in usr_list:
    if char not in punctuation:
        no_punc.append(char)

请注意,实际上也没有必要以这种方式使用输入 list。你可以直接迭代你的usr_str

【讨论】:

  • 非常感谢蒂姆,这似乎是一个简单的解决方法,我理解这两种方式。我的作业指定使用循环,所以第一种方法必须是我使用的方法,但很高兴知道还有更简单的方法!
  • 不过,使用[:] 可能太晦涩难懂,所以我只是添加了另一种方式 - 它对您来说会更加明显;-) 并添加了另一种方式来摆脱其中一个列表。
【解决方案2】:

这可以使用str.translate 方法来完成:

In [10]: 'Testing!!!!, )'.translate(str.maketrans('', '', string.punctuation))
Out[10]: 'Testing '

【讨论】:

    猜你喜欢
    • 2015-12-07
    • 2021-11-28
    • 2015-08-02
    • 2014-08-02
    • 2022-01-14
    • 1970-01-01
    • 2011-11-05
    • 1970-01-01
    • 2015-11-16
    相关资源
    最近更新 更多