Reputation: 9643
I use the code to strip a line of text from punctuation:
line = line.rstrip("\n")
line = line.translate(None, string.punctuation)
The problem is that words like doesn't
turn to doesnt
so now I want to remove the punctuation only between words but can't seem to figure out a way to do so. How
should I go about this?
Edit: I thought about using the strip()
function but that will only take effect on the right and left trailing of the whole sentence.
For example:
Isn't ., stackoverflow the - best ?
Should become:
Isn't stackoverflow the best
Instead of the current output:
Isnt stackoverflow the best
Upvotes: 5
Views: 4738
Reputation: 133544
Assuming you consider words as groups of characters separated by spaces:
>>> from string import punctuation
>>> line = "Isn't ., stackoverflow the - best ?"
>>> ' '.join(word.strip(punctuation) for word in line.split()
if word.strip(punctuation))
"Isn't stackoverflow the best"
or
>>> line = "Isn't ., stackoverflow the - best ?"
>>> ' '.join(filter(None, (word.strip(punctuation) for word in line.split())))
"Isn't stackoverflow the best"
Upvotes: 12
Reputation: 843
line = line.translate(None, string.punctuation.replace('\'', ''))
Is this what u want?
Upvotes: -1