Remove whitespace in Python using string.whitespace

后端 未结 5 620
夕颜
夕颜 2020-11-29 19:51

Python\'s string.whitespace is great:

>>> string.whitespace
\'\\t\\n\\x0b\\x0c\\r \'

How do I use this with a string without resor

5条回答
  •  青春惊慌失措
    2020-11-29 20:35

    a starting point .. (although it's not shorter than manually assembling the whitespace circus) ..

    >>> from string import whitespace as ws
    >>> import re
    
    >>> p = re.compile('(%s)' % ('|'.join([c for c in ws])))
    >>> s = "Please \n don't \t hurt \x0b me."
    
    >>> p.sub('', s)
    "Pleasedon'thurtme."
    

    Or if you want to reduce whitespace to a maximum of one:

    >>> p1 = re.compile('(%s)' % ('|'.join([c for c in ws if not c == ' '])))
    >>> p2 = re.compile(' +')
    >>> s = "Please \n don't \t hurt \x0b me."
    
    >>> p2.sub(' ', p1.sub('', s))
    "Please don't hurt me."
    

    Third way, more compact:

    >>> import string
    
    >>> s = "Please \n don't \t hurt \x0b me."
    >>> s.translate(None, string.whitespace[])
    "Pleasedon'thurtme."
    
    >>> s.translate(None, string.whitespace[:5])
    "Please  don't  hurt  me."
    
    >>> ' '.join(s.translate(None, string.whitespace[:5]).split())
    "Please don't hurt me."
    

提交回复
热议问题