How do I replace punctuation in a string in Python?

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

    This answer is for Python 2 and will only work for ASCII strings:

    The string module contains two things that will help you: a list of punctuation characters and the "maketrans" function. Here is how you can use them:

    import string
    replace_punctuation = string.maketrans(string.punctuation, ' '*len(string.punctuation))
    text = text.translate(replace_punctuation)
    

提交回复
热议问题