Python's way of removing Spaces from a string

  • 2020-04-02 13:28:20
  • OfStack

We often encounter a lot of whitespace problems when dealing with strings, one by one to manually delete is not our programmers should do things, today's tip of the article this site to show you how to use Python to remove whitespace in strings.
Let's first create a string variable s with N Spaces left and right, see the code:
>>> s =  "     The home of the script      " 
>>>

Remove string Spaces, there are built-in methods in Python, we don't need to build our own wheels.
Lstrip: remove the Spaces on the left
This string method deletes the space before the start of the string s.
>>> s.lstrip()
' The home of the script    '

Rstrip: remove the space on the right
This built-in method removes all Spaces at the end of a string. See the following example:
>>> s.rstrip()
'     The home of the script '

Strip: remove Spaces on both ends
Sometimes we read the contents of a file, and we have Spaces on each line. Can we remove them all at once? There is a built-in strip() method for character characters.
>>> s =  "     The home of the script      " 
>>> s.strip()
' The home of the script '

Note on this site: you can use the dir(STR) method to get a list of all the methods in the STR string.

Related articles: