TAGS :Viewed: 9 - Published at: a few seconds ago

[ Python Write a loop that creates a new word list, using a string method to strip the words from the list ]

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?

Answer 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.

Answer 2


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)

Answer 3


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()