Best way to strip punctuation from a string

前端 未结 26 1917
日久生厌
日久生厌 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 06:16

    Here's a solution without regex.

    import string
    
    input_text = "!where??and!!or$$then:)"
    punctuation_replacer = string.maketrans(string.punctuation, ' '*len(string.punctuation))    
    print ' '.join(input_text.translate(punctuation_replacer).split()).strip()
    
    Output>> where and or then
    
    • Replaces the punctuations with spaces
    • Replace multiple spaces in between words with a single space
    • Remove the trailing spaces, if any with strip()

提交回复
热议问题