Remove all whitespace in a string

后端 未结 11 1651
一整个雨季
一整个雨季 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)
    

提交回复
热议问题