How do I replace punctuation in a string in Python?

后端 未结 6 1103
长情又很酷
长情又很酷 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:40

    There is a more robust solution which relies on a regex exclusion rather than inclusion through an extensive list of punctuation characters.

    import re
    print(re.sub('[^\w\s]', '', 'This is, fortunately. A Test! string'))
    #Output - 'This is fortunately A Test string'
    

    The regex catches anything which is not an alpha-numeric or whitespace character

提交回复
热议问题