Python String lstrip() Method
The lstrip()
method removes leading characters (characters at the beginning) from a string. By default, it removes leading whitespace characters such as spaces, tabs, and newlines.
Syntax
string.lstrip([chars])
Parameter
chars
(Optional): A string specifying the set of characters to be removed. If this argument is omitted or None
, all leading whitespace characters are removed.
Return
Returns a new string with specified leading characters removed. It doesn’t modify the original string.
Examples
Basic Usage (Removing Whitespaces)
text = " Python is awesome "
stripped_text = text.lstrip()
print(stripped_text) # Output: "Python is awesome "
Removing Specific Characters
text = "xxxPython is awesome!xxx"
stripped_text = text.lstrip("x")
print(stripped_text) # Output: "Python is awesome!xxx"
The lstrip()
method only removes characters from the beginning (left side) of the string.
Removing Multiple Characters
text = "bacPython is awesome!abc"
stripped_text = text.lstrip("abc")
print(stripped_text) # Output: "Python is awesome!abc"
In this example, the lstrip()
method is not removing the exact substring "abc"
from the start. Instead, it removes any combination of the characters "a"
, "b"
, or "c"
from the beginning of the string.
If you need to remove characters only from the end of a string, use the rstrip()
method.
And if you need to remove characters from both the beginning and the end of a string, use the strip()
method.