How do I replace punctuation in a string in Python?

后端 未结 6 1024
长情又很酷
长情又很酷 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条回答
  •  梦毁少年i
    2021-02-01 19:42

    In my specific way, I removed "+" and "&" from the punctuation list:

    all_punctuations = string.punctuation
    selected_punctuations = re.sub(r'(\&|\+)', "", all_punctuations)
    print selected_punctuations
    
    str = "he+llo* ithis& place% if you * here @@"
    punctuation_regex = re.compile('[%s]' % re.escape(selected_punctuations))
    punc_free = punctuation_regex.sub("", str)
    print punc_free
    

    Result: he+llo ithis& place if you here

提交回复
热议问题