How do I replace punctuation in a string in Python?

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

    This workaround works in python 3:

    import string
    ex_str = 'SFDF-OIU .df  !hello.dfasf  sad - - d-f - sd'
    #because len(string.punctuation) = 32
    table = str.maketrans(string.punctuation,' '*32) 
    res = ex_str.translate(table)
    
    # res = 'SFDF OIU  df   hello dfasf  sad     d f   sd' 
    

提交回复
热议问题