Summary of the three functions used in Python to remove Spaces

  • 2020-05-07 19:54:05
  • OfStack

Function: strip()   lstrip()   rstrip()

Removes a space or specified character from a string

1. Default usage: remove Spaces
str.strip ()  : removes Spaces on both sides of a string
str.lstrip () : removes the space to the left of the string
str.rstrip () : removes the space to the right of the string

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

Default usage instance


>>> dodo = " hello boy "

>>> dodo.strip()
'hello boy'

>>> dodo.lstrip()
'hello boy '

>>> dodo.rstrip()
' hello boy'</span>

2. Removes the specified character
str.strip ('do')  : removes the characters specified at both ends of the string
str.lstrip ('do') : used to remove the character specified on the left
str.rstrip ('do') : used to remove the character specified on the right

Each of the three functions can pass in a single argument ('do' for example), specifying the first and last characters to be removed, and the compiler will remove all the corresponding characters on both ends until there is no matching character

Note:
1. When the specified character is removed, Spaces should not appear at the beginning and end. Otherwise, Spaces should be added when parameters are passed in
2. A combination of the specified character representations, such as 'do' for 'dd','do','od','oo','ddd','ooo', etc

Delete character instance


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

>>> dodo.strip('say')
' hello say boy '
>>> dodo.strip('yas')
' hello say boy '

When adding a space to an incoming parameter


>>> dodo.strip('say ')
'hello say bo'

>>> dodo.lstrip('say')
' hello say boy saaayaaas'

>>> dodo.rstrip('say')
'say hello say boy '


Related articles: