Python - String strip (), rstrip (), lstrip ()

You can use strip() in Python to remove certain characters from a string. Other languages, such as Java, also provide strip(), all of which are similar.

Python`s String provides the following functions:

  • strip([chars]): Strips the character passed as an argument to the left and right of the String.
  • lstrip([chars]): Removes the character passed as an argument from the left side of the String.
  • rstrip([chars]): Removes the character passed as an argument from the right side of the String.

You can also pass no arguments, and if you don`t pass them, you remove the spaces by default from the String.

Remove white spaces

The following code does not pass arguments to strip(). If no argument is passed, strips whitespace from the string.

text = ' Water boils at 100 degrees '
print('[' + text.rstrip() + ']')
print('[' + text.lstrip() + ']')
print('[' + text.strip() + ']')

result

[ Water boils at 100 degrees]
[Water boils at 100 degrees ]
[Water boils at 100 degrees]

Remove same characters

Passing a single character as an argument removes all equivalents of that character. Remove until you get an unequal character.

text = '0000000Water boils at 100 degrees 000'
print(text.lstrip('0'))
print(text.rstrip('0'))
print(text.strip('0'))

result

Water boils at 100 degrees 000
0000000Water boils at 100 degrees
Water boils at 100 degrees

Remove multiple characters

Passing multiple characters as an argument removes all of the same as those characters. Remove until you get an unequal character.

text = ",,,,,123.....water....pp"
print(text.lstrip(',123.p'))
print(text.rstrip(',123.p'))
print(text.strip(',123.p'))

result

water....pp
,,,,,123.....water
water

The following example also passes several characters as arguments.

text = ' Water boils at 100 degrees '
print(text.lstrip(' Water'))
print(text.rstrip(' degrees '))
print(text.strip(' degrees '))
boils at 100 degrees
 Water boils at 100
Water boils at 100

Reference

codechachaCopyright ©2019 codechacha