在Python中删除列表中的标点符号

2 python loops list punctuation

创建一个将字符串转换为列表的Python程序,使用循环删除任何标点符号,然后将列表转换回字符串并打印句子而不带标点符号.

punctuation=['(', ')', '?', ':', ';', ',', '.', '!', '/', '"', "'"]

str=input("Type in a line of text: ")

alist=[]
alist.extend(str)
print(alist)

#Use loop to remove any punctuation (that appears on the punctuation list) from the list

print(''.join(alist))
Run Code Online (Sandbox Code Playgroud)

这就是我到目前为止所拥有的.我尝试使用类似的东西:alist.remove(punctuation)但是我得到一个错误说法list.remove(x): x not in list.我一开始没有正确地阅读这个问题,并意识到我需要通过使用循环来完成这个,所以我在评论中添加了这个,现在我被卡住了.然而,我成功地将它从列表转换回字符串.

roi*_*ppi 5

import string
punct = set(string.punctuation)

''.join(x for x in 'a man, a plan, a canal' if x not in punct)
Out[7]: 'a man a plan a canal'
Run Code Online (Sandbox Code Playgroud)

说明:string.punctuation预定义为:

'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
Run Code Online (Sandbox Code Playgroud)

其余的是直截了当的理解.A set用于加速过滤步骤.

  • 我将'set`拉出genexp; 否则你要为每个`x`构建它. (2认同)