How to remove punctuation in python?

ctrlaltdel picture ctrlaltdel · Dec 7, 2018 · Viewed 19.6k times · Source

I've a problem:

E.x. I have a sentence

s = "AAA? BBB. CCC!" 

So, I do:

import string
table = str.maketrans('', '', string.punctuation)
s = [w.translate(table) for w in s]

And it's all right. My new sentence will be:

s = "AAA BBB CCC"

But, if I have input sentence like:

s = "AAA? BBB. CCC! DDD.EEE"

after remove punctuation the same method as below I'll have

s = "AAA BBB CCC DDDEEE"

but need:

s = "AAA BBB CCC DDD EEE"

Is any ideas/methods how to solve this problem?

Answer

alpharoz picture alpharoz · Dec 7, 2018

You can also do it like this:

punctuation = "!@#$%^&*()_+<>?:.,;"  # add whatever you want

s = "AAA? BBB. CCC!" 
for c in s:
    if c in punctuation:
        s = s.replace(c, "")

print(s)

>>> "AAA BBB CCC"