SoFunction
Updated on 2024-11-12

A short summary of the use of three functions for removing spaces in Python

Functions: strip() lstrip() rstrip()

Function: Removes spaces or specified characters from a string.

I. Default usage: removing spaces
() : Remove spaces from both sides of the string.
() : Remove the space on the left side of the string.
() : Remove spaces from the right side of the string.

Note: Spaces here contain '\n', '\r', '\t', ' '

Default Usage Example

>>> dodo = " hello boy "

>>> ()
'hello boy'

>>> ()
'hello boy '

>>> ()
' hello boy'</span>

II. Removal of specified characters
('do'): removes the specified characters from both ends of the string.
('do'): Used to remove the character specified on the left.
('do'): Used to remove the character specified on the right.

All three functions can be passed a parameter (here 'do' as an example) specifying the first and last characters to be removed, and the compiler will remove all the corresponding characters at both ends until there are no matches

Notes:
1. Remove the specified characters can not appear at the beginning and end of the space, otherwise the incoming parameters also need to add spaces
2. A combination of the specified characters, such as 'do' means 'dd', 'do', 'od', 'oo', 'ddd', 'ooo', and so on.

Example of Removing Characters

>>> dodo = "say hello say boy saaayaaas"

>>> ('say')
' hello say boy '
>>> ('yas')
' hello say boy '

# When spaces are added to incoming parameters

>>> ('say ')
'hello say bo'

>>> ('say')
' hello say boy saaayaaas'

>>> ('say')
'say hello say boy '