Remember
lstrip() removes leading whitespace by default. Its chars argument specifies a set of removable characters, not a prefix.
lstrip() removes leading whitespace by default. Its chars argument specifies a set of removable characters, not a prefix.
Follow the example, change its sample, and compare what happens.
Explain the result and test your understanding.
Focus on how the names, objects, and calculations change. We’ll inspect the printed output in the next section.
Follow the code and watch its state change. Guided simulation.
text = 'ababa tea'
result = text.lstrip("ab ")
print(result)Top-level scope
'ababa tea'Object 2 · str'tea'lstrip() removes leading whitespace by default. Its chars argument specifies a set of removable characters, not a prefix.
(no output)
What do you expect this program to print?
EXAMPLE INSTRUCTIONS
text = 'ababa tea'
result = text.lstrip("ab ")
print(result)
|
v
DISPLAYED RESULT
tea
FINAL BINDINGS
text --> object 1 (str)
result --> object 2 (str)
object 1: 'ababa tea'
object 2: 'tea'Choose a different sample input, then follow every step through to the output. Before revealing it, predict what the program will display.
Choose a sample and follow its execution. Guided simulation.
text = 'ababa tea'
result = text.lstrip("ab ")
print(result)Top-level scope
'ababa tea'Object 2 · str'tea'The example has finished. Compare the final output with the values and references above.
tea
What do you expect this program to print?
text = 'ababa tea'
result = text.lstrip("ab ")
print(result)lstrip() MethodThe lstrip() method in Python removes all leading characters (default is whitespace) from the beginning (left side) of the string.
string.lstrip([chars])
chars (optional): A string specifying the set of characters to remove. If not provided, it removes leading whitespace.text = " hello world"
print(text.lstrip())
hello world
text = "www.example.com"
print(text.lstrip("w."))
example.com
Why? Because lstrip("w.") removes all characters 'w' and '.' from the beginning until it hits a character not in the set.
0s, #s, or ws from the beginning of stringslstrip("abc") removes any combination of 'a', 'b', or 'c' from the start – not the full string "abc"String cleaning is a frequent task in data preprocessing. Know how lstrip(), rstrip(), and strip() differ.
string.lstrip() removes unwanted characters from the beginning of the stringWrite a program to clean user input that may have leading dashes or spaces:
user_input = "-- Hello Python"
cleaned = user_input.lstrip("- ").strip()
print("Cleaned:", cleaned)
Cleaned: Hello Python
Connect what you noticed in the example with the idea below.
lstrip() removes leading whitespace by default. Its chars argument specifies a set of removable characters, not a prefix.
lstrip("ab") removes exactly one literal ab prefix.
This is the misconception to avoid.Reference checks are optional and do not count toward course progress.