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.
if 'Alex' == 'Alex ': print ("Hello Alex!") else: print ("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 in these three functions.
|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 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.
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())
Chris Gayle Chris Gayle Chris Gayle