Lesson 05
lstrip(), rstrip(), and strip()
Learn how to remove spaces and unwanted characters from the left, right, or both ends of a string using visual memory diagrams.
What you'll learn
| Topic | Focus |
|---|---|
lstrip() |
Remove from the left |
rstrip() |
Remove from the right |
strip() |
Remove both sides |
| Space cleanup | Use split() + join() |
Visual roadmap
All three methods remove characters from the edges, not the middle.
Easy memory: L = Left · R = Right · Strip = Both
1. lstrip() → Left strip
Removes whitespace (or characters) from the beginning of the string.
s = " Python"
print(repr(s))
# ' Python'
s = s.lstrip()
print(repr(s))
# 'Python'Character count:
| Before | After | |
|---|---|---|
| Length | 10 characters | 6 characters |
2. rstrip() → Right strip
Removes whitespace from the end of the string.
s = "Python "
s = s.rstrip()
print(repr(s))
# 'Python'Memory: R = Right = End
3. strip() → Both sides
Removes characters from both the beginning and end.
s = " Python "
s = s.strip()
print(repr(s))
# 'Python'Memory formula:
lstrip() vs rstrip() vs strip()
| Method | Removes | Visual |
|---|---|---|
lstrip() |
Left only | [spaces]Python |
rstrip() |
Right only | Python[spaces] |
strip() |
Both sides | [spaces]Python[spaces] |
4. Remove custom characters
strip() is not limited to spaces. You can remove any character from the edges.
s = "++++++++PYTHON+++++++"
print(s.strip("+"))
# PYTHONAnother example:
s = "###Hello###"
print(s.strip("#"))
# HelloImportant: It removes characters only from the edges, not the middle.
5. Cleaning messy spaces
strip() removes outer spaces, but middle spaces remain.
s = "Nirkar Behra "
s = s.strip()
print(repr(s))
# 'Nirkar Behra'
clean = " ".join(s.split())
print(clean)
# Nirkar BehraHow it works:
Playground example
s = " Python "
print(repr(s), len(s))
print(repr(s.strip()), len(s.strip()))
name = "Nirkar Behra "
print(" ".join(name.split()))Expected output:
' Python ' 13
'Python' 6
Nirkar BehraUse the lesson playground at the bottom of the page to run this code live.
Quick knowledge check
-
Which method removes spaces only from the right?
Answer:rstrip() -
Does
strip()remove spaces in the middle?
Answer: No. It only removes leading and trailing characters. -
How do you convert
"a b c"into"a b c"?
Answer:
" ".join(s.split())30-second revision sheet
| Method | Easy memory |
|---|---|
lstrip() |
Remove from left |
rstrip() |
Remove from right |
strip() |
Remove both sides |
split() + join() |
Clean middle spaces |
Interview shortcut: Left → lstrip() · Right → rstrip() · Both → strip() · Middle spaces → split() + join()
Next: Split and Join.
Loading playground…