0

PROBLEM 4. Write a loop that creates a new word list, using a string method to strip the words from the list created in Problem 3 of all leading and trailing punctuation. Hint: the string library, which is imported above, contains a constant named punctuation. Three lines of code.

Okay, I have done the code as follows:

import string
text = ("There once was a man in Idaho, he invented the potato.")
listWords = text.split() #problem3
for i in string.punctuation:
    listWords = text.replace(i,"") #problem4

This code works, but it only removes quotations. How do I remove other forms of punctuation?

Talvalin
  • 7,789
  • 2
  • 30
  • 40
Timothy
  • 29
  • 1
  • 1
  • 8
  • possible duplicate of [Best way to strip punctuation from a string in Python](http://stackoverflow.com/questions/265960/best-way-to-strip-punctuation-from-a-string-in-python) – Talvalin Feb 27 '15 at 02:22
  • You already have a for loop. Just combine your code with the linked duplicate and you should be fine. On a different note, your code does not work as is. – Talvalin Feb 27 '15 at 02:31

3 Answers3

1

You have a for loop. The problem is that if you do x = y.replace(foo,bar) inside a loop, you overwrite x each time. If you do text = text.replace(i,""), that will incrementally remove the punctuation.

Foon
  • 6,148
  • 11
  • 40
  • 42
1

First of all, those quotations are not a part of this text. This is just how this string variable is defined. So you are only looking on , and . here. You can clearly see it by printing your text word by word:

for word in listWords:
    print word

To remove any punctuation signs:

''.join(x for x in text if x not in string.punctuation)
Eugene S
  • 6,709
  • 8
  • 57
  • 91
0

It might be simpler to remove the punctuation from the sentence first, then to split the words up. For example:

import string
text = ("There once was a man in Idaho, he invented the potato.")
out = text.translate(string.maketrans("",""), string.punctuation)
listWords = text.split()
Talvalin
  • 7,789
  • 2
  • 30
  • 40