The lstrip
method will remove a set of leading characters in a string and return a new string.
string.lstrip([chars_to_remove])
The lstrip
method will loop through all the characters of a string and check if the current character of the string is present in the passed chars_to_remove
.
If the current character is present in the chars_to_remove
, then that character will be removed.
If the current character is not present, then the looping is stopped.
chars
: This is the set of characters to be removed from the leading position (start) of the string. It is an optional argument. By default, the leading spaces are removed.
A new string in which the passed set of characters are removed.
# Example 1string = " space at the start is removed "print(string.lstrip(), "."); #space at the beginning of the string is removed# Example 2string = "space set";print(string.lstrip("s")); #pace set# Example 3string = "ss sports";print(string.lstrip("s ")); #ports
string = " space at the start is removed ";
string.lstrip();
In the code above, we have a string with whitespace
at the start and end. When we call the lstrip
method without a argument, the space at the beginning of the string is removed.
string = "space set";
string.lstrip("s"); #pace set
In the code above, we have a space set
string and call the lstrip('s')
method. The lstrip
method will loop the string space set
:
First char: s
is present in the passed argument, so it is removed from the string.
Second char: p
is not present in the passed argument, so looping is stopped and the string pace set
is returned.
string = "ss sports";
string.lstrip("s ");
In the code above, we have an ss sports
string and call the lstrip('s ')
method. The lstrip
method will loop the string ss sports
:
First character: s
is present in the passed argument, so it is removed from the string. Now the result string is s sports
.
Second character: s
is present in the passed argument, so it is removed from the string. Now the result string is ' sports'
.
Third character: whitespace
is present in the passed argument, so it is removed from the string. Now the result string is sports
.
Fourth character: s
is present in the passed argument, so it is removed from the string. Now the result string is ports
.
Fifth character: p
is not present in the passed argument, so looping is removed. The result string ports
is returned.