W3Basic Logo

Python String lstrip() Method

The str.lstrip() method removes the leading characters (characters at the start of the string) specified in the chars argument and returns the copy of the string. If the chars argument is not passed, the lstrip() method removes leading whitespaces in the string.

Example:

# Remove leading characters from a string
text = "#####Hello, World!#####"
print(text.lstrip("#"))  # Output: "Hello, World!#####"

Output

Hello, World!#####

What is Leading and Trailing Characters?

Leading Characters: The characters appearing at the beginning of the string are called leading characters.

Trailing Characters: The characters that appear at the end of the string are called trailing characters.


Syntax

The Syntax of the str.lstrip() function is:

str.lstrip(chars)

Here, str is a string.

Parameters

The str.lstrip() function can take one parameter.

  • chars (optional) - A character or string that needs to be removed at the beginning of the string(leading).

Return Value

The str.lstrip() function returns a copy of a string by stripping the leading characters based on the argument.

  • if the char argument passed is found at the beginning of the string, it would be stripped.
  • If the char argument is not passed, all the whitespaces are stripped at the beginning (leading) of the string.

Example: How to use the lstrip() method in Python

In the first example, we remove the leading whitespaces from the string " Hello, World! " using the lstrip() method.

In the second example, we remove the leading dashes from the string "---Hello, World!---" using the lstrip() method with the argument "-".

In the third example, we remove the leading characters 'x', 'y', and 'z' from the string "xyzHello, World!xyz" using the lstrip() method with the argument "xyz".

In the fourth example, we remove the leading spaces and tab characters from the string " \tHello, World! " using the lstrip() method.

# Remove leading whitespaces from a text
text = "   Hello, World!   "
print(text.lstrip())  # Output: "Hello, World!   "

# Remove leading dashes from a text
text = "---Hello, World!---"
print(text.lstrip("-"))  # Output: "Hello, World!---"

# Remove leading characters specified in a text
text = "xyzHello, World!xyz"
print(text.lstrip("xyz"))  # Output: "Hello, World!xyz"

# Remove leading spaces and tab characters from a string
text = "   \tHello, World!   "
print(text.lstrip())  # Output: "Hello, World!   "

Output

Hello, World!   
Hello, World!---
Hello, World!xyz
Hello, World!   

Reference: Python Official Docs

© 2023 W3Basic. All rights reserved.

Follow Us: