Python String lstrip() Function
The String lstrip()
method removes any whitespace from the beginning (the leading) of the string by default.
You can also specify the characters you want to strip by specifying the chars
parameter of the lstrip()
method.
Syntax
my_string.lstrip(chars)
lstrip() Parameters
Python String lstrip()
function parameters:
Parameter | Condition | Description |
---|---|---|
chars | optional | A string of characters to be removed from the string |
If chars
argument is not provided, all leading whitespaces are removed from the string.
lstrip() Return Value
Python String lstrip()
function returns a copy of the string with leading characters stripped.
All combinations of characters in the chars
parameter are removed from the beginning of the string until the first mismatch.
Examples
Example 1: Strip Whitespaces from Left with lstrip()
The lstrip()
method allows to remove spaces from the left side of a string, returning a new string.
my_str = " Hello "
result = my_str.lstrip()
print(f"'{result}'") # Output: 'Hello '
output
'Hello '
Note that newline \n
, tab \t
and carriage return \r
are also considered whitespace characters!
my_str = " \t\n\r Hello "
result = my_str.lstrip()
print(f"'{result}'") # Output: 'Hello '
output
'Hello '
Example 2: Strip Characters from Left with lstrip()
By specifying the chars
parameter, you can also specify the character you want to strip.
my_str = "aaabbbaaa"
result = my_str.lstrip('a')
print(result) # Output: bbbaaa
output
bbbaaa
Characters are removed from the beginning to the end until reaching a string character that is not contained in the set of characters in chars
parameter.
For example:
my_str = 'xxxxAxxxxAxxxx'
result = my_str.lstrip('x')
print(result) # Output: AxxxxAxxxx
output
AxxxxAxxxx
Example 3: Strip Multiple Characters from Left with lstrip()
The chars
parameter is not a prefix! All combinations of its values are stripped, until reaching a character of the string that is not d in the set of characters in chars
parameter.
For example, let's strip all the characters provided in the argument:
my_str = 'http://www.example.com'
result = my_str.lstrip('hwtp:/.')
print(result) # Output: example.com
output
example.com