Python str.lstrip() function
str.lstrip()
Function in Python
The str.lstrip()
function in Python is used to remove leading (left-side) whitespace or specified characters from the beginning of a string. Unlike str.strip()
which removes both leading and trailing characters, lstrip()
only affects the left side of the string.
Syntax:
string
: The string you want to remove leading characters from.chars
(optional): A string specifying the set of characters to remove. If omitted,lstrip()
will remove leading whitespace (spaces, tabs, newlines) by default.
Example 1: Removing leading whitespace
In this example:
- The leading spaces before
"Hello, Python!"
are removed. - The rest of the string remains unchanged.
Example 2: Removing specific leading characters
Here:
- The
#
characters at the beginning of the string are removed. - Characters in the middle of the string or the right side are not affected.
Example 3: Removing multiple specified characters
In this case:
- The function removes all occurrences of
$
from the left side of the string. - The
!
characters and other content remain unaffected.
Key Points:
str.lstrip()
removes leading (left-side) whitespace characters by default, such as spaces, tabs (\t
), and newlines (\n
).- You can specify which characters to remove by passing them as an argument.
- Only the characters at the beginning (left side) of the string are removed.
- It does not modify the original string but returns a new string with the modifications.
Example 4: Stripping leading newline characters
Here:
- The leading newline characters (
\n\n
) are removed, but the rest of the string remains unchanged.