We often encounter many space-related issues when processing strings. Manually deleting strings one by one is not what our programmers should do. Let's talk about this article, how to Use Python to remove spaces in strings.
First, create a string variable s with around N spaces. See the Code:
Copy codeThe Code is as follows: >>> s = ""
>>>
Remove string spaces. There is a built-in method in Python. We don't need to build the wheel on our own.
Lstrip: removes spaces on the left.
This string method deletes spaces before the start position of string s.
Copy codeThe Code is as follows: >>> s. lstrip ()
'Foot home'
Rstrip: Delete the right-connected Space
This built-in method can delete all spaces at the end of a string. See the following DEMO code:
Copy codeThe Code is as follows: >>> s. rstrip ()
'Foot home'
Strip: removes spaces at both ends.
Sometimes, when we read the content in the file, there are spaces on both sides of each line. Can we remove them all at once? The character has a built-in strip () method.
Copy codeThe Code is as follows: >>> s = ""
>>> S. strip ()
'Foot home'
Tip: You can use the dir (str) method to obtain the list of all methods of the str string.