Lesson 07
startswith() and endswith()
Learn how to verify whether a string begins or ends with specific text using visual memory diagrams and real-world validation examples.
What you'll learn
| Topic | Focus |
|---|---|
startswith() |
Check the beginning |
endswith() |
Check the ending |
| Case sensitivity | Upper ≠ lower |
| Real validation | Files, URLs & emails |
Visual roadmap
These methods only check a string—they never modify it.
Easy memory: Start = Left · End = Right
1. startswith() → Check the beginning
Returns True if the string begins with the given text.
s = "Python is an oop lang"
print(s.startswith("Python")) # True
print(s.startswith("Pyt")) # True
print(s.startswith("lang")) # FalseWhy does "Pyt" work? Because it matches the prefix, not the entire word.
| Check | Result |
|---|---|
"Python" |
True |
"Pyt" |
True |
"Py" |
True |
"lang" |
False |
2. Case sensitivity
Python compares characters exactly.
s = "Python is an oop lang"
print(s.startswith("Python")) # True
print(s.startswith("python")) # FalseCase-insensitive solution:
s = "Python is an oop lang"
print(s.lower().startswith("python"))
# TrueConvert both sides to the same case when case does not matter.
3. endswith() → Check the ending
Returns True if the string finishes with the given text.
s = "Python is an oop lang"
print(s.endswith("lang")) # True
print(s.endswith("ng")) # True
print(s.endswith("g")) # True
print(s.endswith("la")) # FalseSuffix matching:
| Check | Result |
|---|---|
"lang" |
True |
"ng" |
True |
"g" |
True |
"la" |
False |
4. startswith() vs endswith()
They inspect opposite sides of the string.
| Method | Looks at | Returns |
|---|---|---|
startswith() |
Beginning | True / False |
endswith() |
Ending | True / False |
5. Real-world applications
These methods are commonly used for validation.
name.endswith(".py")url.startswith("https://")email.endswith("@gmail.com")line.startswith("#")Playground
Copy and run this example.
s = "Python is an oop lang"
print("startswith Python:", s.startswith("Python"))
print("startswith python:", s.startswith("python"))
print("endswith lang:", s.endswith("lang"))
print("endswith ng:", s.endswith("ng"))Expected output:
startswith Python: True
startswith python: False
endswith lang: True
endswith ng: TrueUse the lesson playground at the bottom of the page to run this code live.
Quick knowledge check
-
Is
"Python is an oop lang".startswith("python")True?
Answer: No — it is case-sensitive. -
Does
"hello.txt".endswith(".txt")return True?
Answer: Yes. -
Do these methods modify the string?
Answer: No — they only return True or False.
30-second visual revision
| Method | Easy memory |
|---|---|
startswith() |
Check the beginning |
endswith() |
Check the ending |
| Return type | Boolean (True / False) |
| Case | "Python" ≠ "python" |
Interview shortcut: Start → startswith() · End → endswith() · Both are Boolean checks and never change the string.
Loading playground…