// Tutorial //

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

Published on August 3, 2022
Default avatar
By Pankaj
Developer and author at DigitalOcean.
Python Trim String - rstrip(), lstrip(), strip()

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Python provides three methods that can be used to trim whitespaces from the string object.

Python Trim String

  • strip(): returns a new string after removing any leading and trailing whitespaces including tabs (\t).
  • rstrip(): returns a new string with trailing whitespace removed. It’s easier to remember as removing white spaces from “right” side of the string.
  • lstrip(): returns a new string with leading whitespace removed, or removing whitespaces from the “left” side of the string.

All of these methods don’t accept any arguments to remove whitespaces. If a character argument is provided, then they will remove that characters from the string from leading and trailing places. Let’s look at a simple example of trimming whitespaces from the string in Python.

s1 = '  abc  '

print(f'String =\'{s1}\'')

print(f'After Removing Leading Whitespaces String =\'{s1.lstrip()}\'')

print(f'After Removing Trailing Whitespaces String =\'{s1.rstrip()}\'')

print(f'After Trimming Whitespaces String =\'{s1.strip()}\'')


String ='  abc  '
After Removing Leading Whitespaces String ='abc  '
After Removing Trailing Whitespaces String ='  abc'
After Trimming Whitespaces String ='abc'

Let’s look at some more examples with strings having a new-line and tabs.

>>> s1 = '  X\n  Y  \nZ  \t'
>>> s1.strip()
'X\n  Y  \nZ'
>>> s1.rstrip()
'  X\n  Y  \nZ'
>>> s1.lstrip()
'X\n  Y  \nZ  \t'

You can check out more Python string examples from our GitHub Repository.

If you’ve enjoyed this tutorial and our broader community, consider checking out our DigitalOcean products which can also help you achieve your development goals.

Learn more here

About the authors
Default avatar


Developer and author at DigitalOcean.

Still looking for an answer?

Was this helpful?

Thank you very much for these examples. I was trying to understand the differences and your explanation was very easy to understand. I’ll check out more of your pages.

- Anna

    Is there a stock Python function that removed redundant spaces? For example: “Hello world” becomes “Hello Word”

    - SoCalDude