Python String lstrip() Method – Tutorial with Examples

Python String lstrip() Method

Python provides several string methods to manipulate and process strings. One of them is the lstrip() method, which is used to remove characters from the left side of a string.

Syntax

The syntax for using the lstrip() method is as follows:

str.lstrip([chars])

The lstrip() method takes an optional parameter chars, which specifies the set of characters to be removed from the beginning of the string. If the chars parameter is not provided, the method removes whitespace characters (spaces, tabs, and newlines) from the beginning of the string.

The lstrip() method returns a new string with the specified characters removed from the left side of the original string.

Examples

Here are some examples to illustrate the usage of the lstrip() method:

Example 1: Removing whitespace characters from the beginning of a string

string = "    Hello, World!"
result = string.lstrip()
print(result)

Output:

Hello, World!

In this example, the lstrip() method is used to remove the whitespace characters from the beginning of the string.

Example 2: Removing a specific set of characters from the beginning of a string

string = "%%%Hello, World!"
result = string.lstrip("%")
print(result)

Output:

Hello, World!

In this example, the lstrip() method is used to remove the percentage sign (“%”) from the beginning of the string.

Example 3: Removing multiple characters from the beginning of a string

string = "##$$$Hello, World!"
result = string.lstrip("#$%")
print(result)

Output:

Hello, World!

In this example, the lstrip() method is used to remove the characters “#”, “$”, and “%” from the beginning of the string.

Use Cases

The lstrip() method can be useful in many situations. Some common use cases include:

  • Removing whitespace characters from the beginning of a string before further processing.
  • Removing a specific set of characters from the beginning of a string, such as a specific punctuation mark or prefix.
  • Stripping a string of a particular set of characters on the left side, in order to make it easier to compare with another string.

Overall, the lstrip() method is a useful tool in manipulating and processing strings in Python.

Leave a Reply

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