This guide explains str.lstrip Method: Usage and Examples through a focused example and practical reasoning. No prior knowledge of this specific operation is required.
Understanding the Concept
str.lstrip(chars=None) removes leading whitespace by default. With chars, it removes any leading characters belonging to the supplied set; the argument is not a literal prefix.
When You Would Use This
Clean leading spaces from a pasted identifier.
Step-by-Step Example
raw_identifier = " INV-105 "
print(repr(raw_identifier.lstrip()))
print("www.example.com".lstrip("w."))
How the Example Works
The first result has no leading spaces but retains trailing spaces. The second demonstrates that the characters w and . are removed repeatedly from the start, not as one exact prefix.
Example Output
'INV-105 '
example.com
Try It Yourself
Use .removeprefix() when you need to remove exactly "ID-" from a code.
Common Beginner Mistakes
- Using
lstrip("www.")as though it removed exactly the prefixwww.. - Expecting trailing characters to be removed too.
- Assuming the argument is a regular expression.
Key Takeaways
str.lstrip(chars=None)removes leading whitespace by default.- The first result has no leading spaces but retains trailing spaces.
- Avoid this mistake: Using
lstrip("www.")as though it removed exactly the prefixwww..