🕯️ Magic Note
The .endswith() method returns True if the string ends with the specified suffix and False otherwise. It is case sensitive, so “.jpg” is different from “.JPG”. You can also pass a tuple of suffixes to check multiple endings at once.
- Works on any string, not just filenames
- Can check multiple endings with a tuple: .endswith((“.jpg”, “.png”, “.gif”))
- Supports slicing with start and end parameters: .endswith(“.jpg”, 0, 10)
- Case sensitive, use .lower() before checking for case insensitive comparison
To make it case insensitive, convert to lowercase first: if filename.lower().endswith((“.jpg”, “.png”)).
| String | Suffix | Result |
|---|---|---|
| “photo.jpg” | “.jpg” | True |
| “document.pdf” | “.pdf” | True |
| “image.JPG” | “.jpg” | False |
| “data.txt” | “.csv” | False |
| “archive.tar.gz” | “.gz” | True |
Python
# Check a single file extension
filename = “sunset.jpg”
print(filename.endswith(“.jpg”))
# Output: True
Python
# Case sensitivity trap
filename = “image.JPG”
print(filename.endswith(“.jpg”))
# Output: False
print(filename.lower().endswith(“.jpg”))
# Output: True
Python
# Check multiple extensions at once
filename = “portrait.png”
print(filename.endswith((“.jpg”, “.png”, “.gif”)))
# Output: True
- Forgetting that .endswith() is case sensitive, then wondering why “.JPG” files are ignored
- Passing multiple extensions as separate arguments instead of a tuple, causing a TypeError
- Assuming .endswith() works on Path objects, you need to convert to string with str(path) or use path.suffix
⚡ Whisper
The ending holds the key. What looks like a simple dot and three letters decides the fate of your spell. Read the final breath before you act. Filter the unseen. Focus only on what matters.