Skip to content

Best way to strip punctuation from a string

One way to strip punctuation from a string is to use the str.translate() method in combination with the string.punctuation constant.

String translate and punctuate in Python

python
import string
s = "Hello, World!"
s = s.translate(str.maketrans('', '', string.punctuation))
print(s)

output:

output

console
Hello World

Another way is to use re.sub() method of regular expression module, which you can use to replace all punctuation characters with a space.

Use regex module to replace all punctuation charactars with space in Python

python
import re
s = "Hello, World!"
s = re.sub(r'[^\w\s]','',s)
print(s)

output:

another output

console
Hello World

You can also use list comprehension to iterate over the string and only keep the characters that are not in the string of punctuation marks:

Use list comprehension to iterate over the string and only keep the characters that are not in the string of punctuation marks in Python

python
import string
s = "Hello, World!"
s = ''.join([c for c in s if c not in string.punctuation])
print(s)

output:

the same output

console
Hello World

You can choose the way that suits you best.

Dual-run preview — compare with live Symfony routes.