How do I replace punctuation in a string in Python?

后端 未结 6 1032
长情又很酷
长情又很酷 2021-02-01 19:31

I would like to replace (and not remove) all punctuation characters by \" \" in a string in Python.

Is there something efficient of the following flavo

6条回答
  •  攒了一身酷
    2021-02-01 19:57

    Modified solution from Best way to strip punctuation from a string in Python

    import string
    import re
    
    regex = re.compile('[%s]' % re.escape(string.punctuation))
    out = regex.sub(' ', "This is, fortunately. A Test! string")
    # out = 'This is  fortunately  A Test  string'
    

提交回复
热议问题