Chapter 16: Strip Method

The strip() method is used to remove leading and trailing whitespace from a string. It is called using the dot operator.

 

To remove leading spaces (from the left), use the lstrip() method.

 

name   = "   Free Learning   "
string = "***|FL|***"
print(name+string)           # normal
Output:    Free Learning   ***|FL|***
print(name.lstrip()+string)  # left space removed
Output: Free Learning   ***|FL|***

 

To remove trailing spaces (from the right), use the rstrip() method.

 

name   = "   Free Learning   "
string = "***|FL|***"
print(name+string)          # normal
Output:    Free Learning   ***|FL|***
print(name.rstrip()+string) # right space removed
Output:    Free Learning***|FL|***

 

To remove spaces from both ends, use the strip() method.

 

name   = "   Free Learning   "
string = "***|FL|***"
print(name+string)          # normal
Output:    Free Learning   ***|FL|***
print(name.strip()+string)  # both side space removed
Output: Free Learning***|FL|***