How to remove all punctuation marks in a string? (Python)

For instance:

asking="hello! what your name?"

Can I do it?

asking.strip("!'?")
+5
source share
4 answers

Actually a simple implementation:

out = "".join(c for c in asking if c not in ('!','.',':'))

and keep adding any other punctuation marks.

A more efficient way would be

import string
stringIn = "string.with.punctuation!"
out = stringIn.translate(stringIn.maketrans("",""), string.punctuation)

Edit: Here are some more discussions of efficiency and other implementations: Best way to block punctuation from a string in Python

+14
source
import string

asking = "".join(l for l in asking if l not in string.punctuation)

a string.punctuation.

+12
source

, .

asking="hello! what your name?"
asking = ''.join([c for c in asking if c not in ('!', '?')])
print asking
0

The strip will not work. It removes only leading and trailing instances, and not everything in between: http://docs.python.org/2/library/stdtypes.html#str.strip

Fun with a filter:

import string
asking = "hello! what your name?"
predicate = lambda x:x not in string.punctuation
filter(predicate, asking)
0
source

All Articles