Spaces are also considered as a character inside a string, and sometimes unnecessary spaces in the string cause wrong results.



For example, instead of typing 'Alex', a person typed his name 'Alex  ' (see two spaces at the end of the string), and if we compare them using the '==' operator.

Example:

if 'Alex' == 'Alex  ':
    print ("Hello Alex!")
else:
    print ("Not found")

Output:

Not found

The output of the above program will be 'not found', and this way, additional spaces may lead to wrong results. Therefore, such blank spaces should be removed from the string before being used. This is possible by using rstrip(), lstrip() and strip() methods in Python. These three functions do the same thing, but there is a slight difference between these three functions.

Function Description
rstrip() rstrip() method removes whitespace at the end of a string.
lstrip() lstrip() method removes whitespace at the beginning of a string.
strip() strip() method removes whitespace at the beginning and end (both sides) of a string.

These three methods do not remove empty spaces between the strings and are usually used where the input is taken from the user.

Example:

name = '  Chris Gayle  '
#remove spaces from left
print (name.lstrip())

#remove spaces from right
print (name.rstrip())

#remove spaces from both side
print (name.strip())

Output:

Chris Gayle  
  Chris Gayle
Chris Gayle


Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram