Python - How to remove punctuation between words

I use code to extract a line of text from punctuation:

line = line.rstrip("\n") line = line.translate(None, string.punctuation) 

The problem is that words like doesn't appeal to doesnt , so now I want to remove punctuation only between words, but I can’t figure out how to do this. How should I go about it?

Edit: I was thinking about using the strip() function, but this will only affect the right and left trailing of the entire sentence.

For instance:

 Isn't ., stackoverflow the - best ? 

It should become:

 Isn't stackoverflow the best 

Instead of the current output:

 Isnt stackoverflow the best 
+4
source share
2 answers

Assuming you treat 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" 
+11
source
 line = line.translate(None, string.punctuation.replace('\'', '')) 

That's what you need?

-1
source

All Articles