startswith, endswith
- Python course
- Beginner
- Lesson 92/116
- 4 min
Learn prefix/suffix checks with startswith and endswith.
startswith and endswith
startswith checks whether a string begins with a substring. endswith checks whether it ends:
"hello.py".endswith(".py") # True
"http://...".startswith("http") # TrueBoth return bool. These methods are very common for file extension checks, URL protocol checks and similar tasks.
Multiple substrings can be given as a tuple; if any matches, True is returned.
Multiple checks
Multiple substrings can be given as a tuple:
name = "photo.jpg"
name.endswith((".jpg", ".png", ".gif")) # TrueThis is very useful when checking multiple options like file extensions. Using a tuple is shorter than writing multiple or() conditions.
Similarly, startswith also accepts a tuple.
Practice Check with endswith
Assign "photo.jpg" to filename. Assign filename.endswith(".jpg") to is_image. Then print print(is_image).
Starter code
# Check with endswithSample solution
filename = "photo.jpg"
is_image = filename.endswith(".jpg")
print(is_image)Expected output
True
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the endswith call
is_py = "hello.py".____(".py")
is_py = "hello.py".endswith(".py")
Explanation: endswith(".py") checks the ending.
2 What does "hello.py".endswith(".py") return?
- False
- True Correct answer
- ".py"
- Raises an error
Explanation: The string ends with ".py"; True is returned.
3 Match startswith and endswith
| Term | Meaning |
|---|---|
startswith |
Start check |
endswith |
End check |
tuple |
Multiple options |
bool |
Return type |