In this tutorial, we’ll learn what Python string lstrip() method is and how to properly use it. We’ll go through multiple Python code examples to understand how lstrip() method works.
Introduction: Python String lstrip() Method
This method returns a string after removing the leading characters from it and its based on the string passed as an argument to this method.
Syntax of lstrip() Method
string.lstrip(str(optional))
- Python string lstrip method supports a string parameter.
- This string parameter is optional and it specifies the characters to be removed from the left side of string.
- If no argument is passed to lstrip method then only the whitespaces from left are removed from string.
- Python string lstrip method return a new string with leading characters stripped(only whitespaces will be removed from left if no argument is passed).
Example 1: lstrip() Method with no Parameter
print('Python'.lstrip()) print(' Python'.lstrip()) print(' Python '.lstrip()) print(' Python Programming.'.lstrip())
Output
Python Python Python Python Programming.
Python string lstrip() method remove whitespaces from left as no string argument is passed to it.
Example 2: lstrip() Method with String Parameter
print(' rpPython'.lstrip('r')) // no whitespace defined so r will not be removed print(' rpPython'.lstrip(' r')) // r removed from leading as whitespace is defined(both in string and argument) print(' rrpPython'.lstrip('r ')) // all the r's are removed from leading print(' rpPython'.lstrip('rpP')) // whitespace defined in string but not in argument, so no removal print(' rpPython'.lstrip(' rpP')) // rpP removed print(' rpPython'.lstrip('rpP ')) // rpP removed print(' rpPython'.lstrip(' thn')) // specified arguments characters not found in leading, so no removal print(' rpPython'.lstrip('thn ')) // no removal as characters not found in leading print(' rpPython'.lstrip('rthn ')) // r removed only, other characters don't match print(' rpPython'.lstrip(' rthn ')) // r removed only, other characters don't match print(' rpPython'.lstrip(' thr')) // r removed only, other characters don't match so no removal of them
Output
rpPython pPython pPython rpPython ython ython rpPython rpPython pPython pPython pPython
You can try it with other examples as well to better understand how Python string lstrip() method works with string argument.
Example 3: lstrip() Method Return Value
val=' Python Programming Language' returnedVal=val.lstrip('Pytho Language') print(returnedVal)
Output
rogramming Language
Python string lstrip method return a new string with all the matching specified characters(passed as a string argument to lstrip method) stripped from leading.
Click here to learn how Python string rstrip() method works.
Conclusion
To conclude this tutorial, hope you now have a detailed practical understanding of how to properly use Python string lstrip method. I’d be very delighted to have your feedback on this post. Thank you for reading it.