How to Remove Punctuations From a String in Python?

PythonProgramming

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

Example

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

Output

This will give us the output −

string With Punctuation

Example

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

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

Output

This will give us the output −

string With Punctuation
raja
Published on 20-Apr-2018 11:27:38
Advertisements