Best way to strip punctuation from a string

前端 未结 26 1872
日久生厌
日久生厌 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:04
    myString.translate(None, string.punctuation)
    
    0 讨论(0)
  • 2020-11-21 06:07

    Regular expressions are simple enough, if you know them.

    import re
    s = "string. With. Punctuation?"
    s = re.sub(r'[^\w\s]','',s)
    
    0 讨论(0)
  • 2020-11-21 06:10
    >>> s = "string. With. Punctuation?"
    >>> s = re.sub(r'[^\w\s]','',s)
    >>> re.split(r'\s*', s)
    
    
    ['string', 'With', 'Punctuation']
    
    0 讨论(0)
  • 2020-11-21 06:12

    A one-liner might be helpful in not very strict cases:

    ''.join([c for c in s if c.isalnum() or c.isspace()])
    
    0 讨论(0)
  • 2020-11-21 06:12

    Considering unicode. Code checked in python3.

    from unicodedata import category
    text = 'hi, how are you?'
    text_without_punc = ''.join(ch for ch in text if not category(ch).startswith('P'))
    
    0 讨论(0)
  • 2020-11-21 06:15

    This might not be the best solution however this is how I did it.

    import string
    f = lambda x: ''.join([i for i in x if i not in string.punctuation])
    
    0 讨论(0)
提交回复
热议问题