Best way to strip punctuation from a string

前端 未结 26 1919
日久生厌
日久生厌 2020-11-21 05:39

It seems like there should be a simpler way than:

import string
s = \"string. With. Punctuation?\" # Sample string 
out = s.translate(string.maketrans(\"\",\         


        
26条回答
  •  旧时难觅i
    2020-11-21 05:55

    For the convenience of usage, I sum up the note of striping punctuation from a string in both Python 2 and Python 3. Please refer to other answers for the detailed description.


    Python 2

    import string
    
    s = "string. With. Punctuation?"
    table = string.maketrans("","")
    new_s = s.translate(table, string.punctuation)      # Output: string without punctuation
    

    Python 3

    import string
    
    s = "string. With. Punctuation?"
    table = str.maketrans(dict.fromkeys(string.punctuation))  # OR {key: None for key in string.punctuation}
    new_s = s.translate(table)                          # Output: string without punctuation
    

提交回复
热议问题