Python trim string

The trim method is used to trim whitespaces from both sides of a given string. Python provides three methods to do so. Below is the list of python trim methods.

  1. strip()
  2. rstript()
  3. lstrip()

1. strip() trim method

The strip method will remove any trailing or leading of a given string including tab (\t) and return a new string.
To test the strip() method. Try the following example:

strOne = '   desert    '

print('without trim method "'+strOne+'"')
print('with trim method "'+strOne.strip()+'"')

# Output
# without trim method "   desert   "
# with trim method "desert"

2. rstrip() trim method

The rstrip method removes the trailing whitespace and returns the new string. In other words, it will remove the whitespace from the right side of the given string. Try the following example:

strOne = '   desert   '

print('without trim method "'+strOne+'"')
print('with rtrim method "'+strOne.rstrip()+'"')

# without trim method "   desert   "
# with trim method "   desert"

3. lstrip() trim method

The lstrip method removes the leading whitespace and returns a new string. In other words, it will remove the whitespace from the left/beginning side of the given string. Try the following example of ltrim:

strOne = '   desert   '

print('without trim method "'+strOne+'"')
print('with trim method "'+strOne.lstrip()+'"')

# without trim method "   desert   "
# with trim method "desert   "