Python ProgrammingPython Programming

How to strip punctuation from a string in Python?

import string
import re
 
# Example 1
s = "Ethnic (279), Responses (3), 2016 Census - 25% Sample"
out = re.sub(r'[^\w\s]', '', s)
print(out)
 
# Example 2
s = "Ethnic (279), Responses (3), 2016 Census - 25% Sample"
for p in string.punctuation:
        s = s.replace(p, "")
print(s)
 
# Example 3
s = "Ethnic (279), Responses (3), 2016 Census - 25% Sample"
out = re.sub('[%s]' % re.escape(string.punctuation), '', s)
print(out)
Sample output of above program.

Ethnic 279 Responses 3 2016 Census 25 Sample
Ethnic 279 Responses 3 2016 Census 25 Sample
Ethnic 279 Responses 3 2016 Census 25 Sample