Best way to strip punctuation from a string

前端 未结 26 1869
日久生厌
日久生厌 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条回答
  •  情歌与酒
    2020-11-21 05:55

    I haven't seen this answer yet. Just use a regex; it removes all characters besides word characters (\w) and number characters (\d), followed by a whitespace character (\s):

    import re
    s = "string. With. Punctuation?" # Sample string 
    out = re.sub(ur'[^\w\d\s]+', '', s)
    

提交回复
热议问题