2

I need to remove all punctuation marks in the string, as a part of bigger program. It is working when I write it serepatly for each mark like this:

words = [word.replace(".", "") for word in words]

But when I am trying to do it in the loop, it is not working.

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

Can you please tell me, what I am doing wrong?

  • 1
    There is no reason to split your string into words for this, remove the punctuation first and then split if you need to (see the dupes) – Chris_Rands May 12 '17 at 07:48
  • 1
    @Chris_Rands thanks, I just need it for further code, was not realizing, that it is causing a trouble. Now it is working. – Elina Schadrin May 12 '17 at 07:58

2 Answers2

4

translate will work for you:

>>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
zipa
  • 27,316
  • 6
  • 40
  • 58
1

Your Problem is

if punc in words:

This checks if one element of the list is punc, not if any of the elements in the list contains punc. Just get rid of that line and it should work.

phogl
  • 494
  • 1
  • 8
  • 16