strip, lstrip, rstrip
- Python course
- Beginner
- Lesson 89/116
- 4 min
Learn to remove edge whitespace with strip.
strip, lstrip, rstrip
strip removes characters from both ends of a string. The default is whitespace:
" hello ".strip() # "hello"
"--hello--".strip("-") # "hello"lstrip removes from the left, rstrip from the right. These methods are commonly used to clean up user input.
strip does not modify the original string; it returns a new one. Strings are immutable in Python, so this rule applies to all string methods.
lstrip vs rstrip
lstrip removes only from the left, rstrip only from the right:
" hello ".lstrip() # "hello "
" hello ".rstrip() # " hello"This is useful when only one side needs cleaning. For example, rstrip is preferred to remove trailing spaces from a line.
All three methods return a new string; they do not change the original.
Practice Clean with strip
Assign " hello " to raw. Assign raw.strip() to clean. Then print print(clean).
Starter code
# Clean with stripSample solution
raw = " hello "
clean = raw.strip()
print(clean)Expected output
hello
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the strip call
clean = " hello ".____()
clean = " hello ".strip()
Explanation: strip() removes leading and trailing spaces.
2 Match the strip methods
| Term | Meaning |
|---|---|
strip |
Both sides |
lstrip |
Left side |
rstrip |
Right side |
new string |
Return value |
3 What does "--hi--".strip("-") return?
- "--hi--"
- "--hi"
- "hi" Correct answer
- "hi--"
Explanation: strip removes '-' from both ends.