我需要删除字符串中的所有标点符号,作为更大程序的一部分。 当我为每个标记编写serepatly时它正在工作:
words = [word.replace(".", "") for word in words]
但是当我尝试在循环中执行它时,它无法正常工作。
line = "I was going to leave her, but in the very last moment I had changed
my mind. Interesting thing, many nice ways to use."
words = line.lower().split()
for punc in [".",","]:
if punc in words:
words = [word.replace(punc, "") for word in words]
print words
你能告诉我,我做错了吗?
答案 0 :(得分:4)
translate
适合您:
>>line = '''I was going to leave her, but in the very last moment I had changed
my mind. Interesting thing, many nice ways to use.'''
>>line = line.translate(None, ',.')
I was going to leave her but in the very last moment I had changed
my mind Interesting thing many nice ways to use
答案 1 :(得分:1)
你的问题是
if punc in words:
这将检查列表中的一个元素是punc
,而不是列表中的任何元素是否包含punc
。只是摆脱那条线,它应该工作。