Remove all whitespace in a string

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

    In addition, strip has some variations:

    Remove spaces in the BEGINNING and END of a string:

    sentence= sentence.strip()
    

    Remove spaces in the BEGINNING of a string:

    sentence = sentence.lstrip()
    

    Remove spaces in the END of a string:

    sentence= sentence.rstrip()
    

    All three string functions strip lstrip, and rstrip can take parameters of the string to strip, with the default being all white space. This can be helpful when you are working with something particular, for example, you could remove only spaces but not newlines:

    " 1. Step 1\n".strip(" ")
    

    Or you could remove extra commas when reading in a string list:

    "1,2,3,".strip(",")
    

提交回复
热议问题