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

Filed Under: Python

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()}\'')

Output:


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 checkout more Python string examples from our GitHub Repository.

Comments

  1. Anna says:

    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.

  2. SoCalDude says:

    Is there a stock Python function that removed redundant spaces?

    For example:

    “Hello world”

    becomes

    “Hello Word”

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages