Computer >> Computer tutorials >  >> Programming >> Python

How to strip down all the punctuation from a string in Python?


The fastest way to strip all punctuation from a string is to use str.translate(). You can use it as follows:

import string
s = "string. With. Punctuation?"
print s.translate(None, string.punctuation)

This will give us the output:

string With Punctuation

If you want a more readable solution, you can explicitly iterate over the set and ignore all punctuation in a loop as follows:

import string
s = "string. With. Punctuation?"
exclude = set(string.punctuation)
s = ''.join(ch for ch in s if ch not in exclude)
print s

This will give us the output:

string With Punctuation