How to Use lstrip Method in Python

Hello Reader, After reading this article, you will be able to know how to Use lstrip Method in Python. Generally, lstrip() is a pre-defined Method of String Class. The lstrip stands for Left Strip of Characters in given String. Where Stripping is removing Characters. So, lstrip removes the specified characters on the left side of the given String.

To know How to Use lstrip Method in Python, we must learn the Syntax and Semantics of that Method. So, let’s have a look at its Syntax and Semantics of lstrip().

Syntax of lstrip() Method:

The Syntax of lstrip() Method is as follows

>>> str.lstrip([chars])

Where str is the String in which we need to remove Characters, chars is the sequence of the Characters to remove from str

lstrip Method works according to given chars as follows

  1. If chars=”” (i.e. Empty String) then lstrip Method removes the Blank Spaces on the Left Side of given String.
  2. If chars=”x” (say ‘x’ is not in String) then lstrip Method returns the Original String without any Modifications.
  3. If chars=’a’ (say ‘a’ is on Left Edge of String) It returns the String without chars.

Now, let’s have a look at the below examples for the above 3 cases.

Case 1: If chars = “” :

Let’s have a glance over the following code

s="   Hello Reader   "  # 'Hello Reader' contains 3 Blank Sapces at both the Ends
b=s.lstrip()            # Returns the s without Spaces at Left Side
print(b)

Here, s is the given String(i.e. ”   Hello Reader   “), b is Auxiliary Variable which is used to store the Stripped String of given String.

Now, the output of the above code will be as follows

Output:

'Hello Reader   '

From the above output, It’s clear that lstrip removed the Blank Spaces of the given string on the Left Edge. Similarly, let’s have a look at the two other cases also.

Case 2: If chars not in str:

In this case, the given characters to remove are not available in the given string. In such situations, it returns the original string as it is. Let’s have a look at that.

s="Hello Reader"
b=s.lstrip("x")
print(b)

Output:

The output of the above code will be as follows

'Hello Reader'
  • lstrip only removes characters if the stream of given characters matches with the Left Edge of the given string.

Now, let’s have a look at the next case of removing characters from a given String.

Case 3: If chars are on Left Edge of str:

s="Hello Reader"
b=s.lstrip("Hello")
print(b)

The output of the above code will be as follows

' Reader'

Since the “Hello” matches with the Left End of s, lstrip removed the whole Characters at the left end and returned the remaining string (i.e. ‘ Reader’).

For further reference, Read also Keyword or Not – Python

Leave a Reply

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