Home » Programming » Python » Python Lstrip Rstrip

Python lstrip and rstrip Methods – With Examples

This short tutorial will show you how to use lstrip and rstrip to remove whitespace (or any other characters) from the beginning/end of strings in Python.

The lstrip and rstrip methods are available on any string type variable in Python 3.

Python lstrip String Method

The lstrip (Left strip) method will remove leading characters from the string – that is, characters starting from the left of the string.

Syntax

Here’s the syntax for the lstrip method:

string.lstrip(characters)

Note that:

  • string can be any string value or variable with a string value
  • characters is an optional parameter for the lstrip method
    • These are the characters that will be stripped from the string, starting from the left.
    • If not specified, white space (spaces, tabs, line returns) are removed by default.
    • Characters will be removed until a character is reached that is NOT specified to be stripped.
    • The process will be halted once a non-stripped character is reached, even if there are matching characters further along in the string.

Example

myText = "       spaces to the left of me!"
print(myText)
print(lstrip(myText))

The above will output:

    spaces to the left of me!
spaces to the left of me!

The second line isn’t indented – because the leading spaces have been removed by lstrip.

Python rstrip String Method

The rstrip (Right strip) method will remove trailing characters from the string – that is, characters starting from the right of the string.

Syntax

Here’s the syntax for the rstrip method (it’s going to look familiar):

string.rstrip(characters)

Note that:

  • string can be any string value or variable with a string value
  • characters is an optional parameter for the rstrip method
    • These are the characters that will be stripped from the string, starting from the right.
    • If not specified, white space (spaces, tabs, line returns) are removed by default.
    • Characters will be removed until a character is reached that is NOT specified to be stripped.
    • The process will be halted once a non-stripped character is reached, even if there are matching characters further along in the string.

Example

myText = "spaces to the right of me!        "
print(myText + "!")
print(rstrip(myText) + "!")

The above will output:

spaces to the right of me!        !
spaces to the right of me!!

The second line doesn’t have that big gap between the exclamation marks – because the trailing spaces in MyText have been removed by rstrip.

SHARE:
Photo of author
Author
I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Comment