Remove all whitespace in a string

后端 未结 11 1639
一整个雨季
一整个雨季 2020-11-22 04:02

I want to eliminate all the whitespace from a string, on both ends, and in between words.

I have this Python code:

def my_handle(self):
    sentence          


        
相关标签:
11条回答
  • 2020-11-22 04:10

    "Whitespace" includes space, tabs, and CRLF. So an elegant and one-liner string function we can use is str.translate:

    Python 3

    ' hello  apple '.translate(str.maketrans('', '', ' \n\t\r'))
    

    OR if you want to be thorough:

    import string
    ' hello  apple'.translate(str.maketrans('', '', string.whitespace))
    

    Python 2

    ' hello  apple'.translate(None, ' \n\t\r')
    

    OR if you want to be thorough:

    import string
    ' hello  apple'.translate(None, string.whitespace)
    
    0 讨论(0)
  • 2020-11-22 04:12

    To remove only spaces use str.replace:

    sentence = sentence.replace(' ', '')
    

    To remove all whitespace characters (space, tab, newline, and so on) you can use split then join:

    sentence = ''.join(sentence.split())
    

    or a regular expression:

    import re
    pattern = re.compile(r'\s+')
    sentence = re.sub(pattern, '', sentence)
    

    If you want to only remove whitespace from the beginning and end you can use strip:

    sentence = sentence.strip()
    

    You can also use lstrip to remove whitespace only from the beginning of the string, and rstrip to remove whitespace from the end of the string.

    0 讨论(0)
  • 2020-11-22 04:12
    import re    
    sentence = ' hello  apple'
    re.sub(' ','',sentence) #helloworld (remove all spaces)
    re.sub('  ',' ',sentence) #hello world (remove double spaces)
    
    0 讨论(0)
  • 2020-11-22 04:14

    For removing whitespace from beginning and end, use strip.

    >> "  foo bar   ".strip()
    "foo bar"
    
    0 讨论(0)
  • 2020-11-22 04:14
    ' hello  \n\tapple'.translate({ord(c):None for c in ' \n\t\r'})
    

    MaK already pointed out the "translate" method above. And this variation works with Python 3 (see this Q&A).

    0 讨论(0)
  • 2020-11-22 04:17

    If you want to remove leading and ending spaces, use str.strip():

    sentence = ' hello  apple'
    sentence.strip()
    >>> 'hello  apple'
    

    If you want to remove all space characters, use str.replace():

    (NB this only removes the “normal” ASCII space character ' ' U+0020 but not any other whitespace)

    sentence = ' hello  apple'
    sentence.replace(" ", "")
    >>> 'helloapple'
    

    If you want to remove duplicated spaces, use str.split():

    sentence = ' hello  apple'
    " ".join(sentence.split())
    >>> 'hello apple'
    
    0 讨论(0)
提交回复
热议问题