Remove all whitespace in a string

后端 未结 11 1675
一整个雨季
一整个雨季 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: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'
    

提交回复
热议问题