【发布时间】: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!!
提前感谢您的帮助!
【问题讨论】:
-
问题是迭代器没有被移回以检查代替被删除的字符的字符。但是,您确实应该使用更简洁的方法,例如 RegEx。
-
嗯,Spencer 说得有道理,而且我对 Python 还是比较陌生,所以我会研究正则表达式。谢谢!
-
如果你不想进入正则表达式,我也推荐@Soon's answer for
string.translate。
标签: python list for-loop python-3.x