0%

🪄 Focus reveals the unseen

Focus isn’t just for lenses. Python checks endings to decide what to reveal. Use .endswith() to test a file’s final breath before casting the next spell.
🔮 if photo.endswith(“.jpg”): focus(photo)

Every file has a signature at the end of its name. The extension tells you what kind of spirit lives inside. .jpg means an image. .py means Python magic. .txt means plain words. The method .endswith() reads only the final syllables of a string. It does not care about what came before. Only the ending matters.

🕯️ 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.

The syntax photo.endswith(“.jpg”) checks if the string photo ends with the exact characters “.jpg”. This is perfect for filtering files, validating inputs, or routing logic based on file types.
  • 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 check multiple extensions, pass a tuple: if filename.endswith((“.jpg”, “.jpeg”, “.png”, “.gif”)).
To make it case insensitive, convert to lowercase first: if filename.lower().endswith((“.jpg”, “.png”)).
StringSuffixResult
“photo.jpg”“.jpg”True
“document.pdf”“.pdf”True
“image.JPG”“.jpg”False
“data.txt”“.csv”False
“archive.tar.gz”“.gz”True
⚠️ The check is exact and case sensitive. “image.JPG”.endswith(“.jpg”) returns False because “JPG” is not “jpg”. Always normalize with .lower() if you need case insensitive matching. Also note that “file.tar.gz”.endswith(“.gz”) returns True even though the extension is technically “.tar.gz”.
Examples

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

Common Mistakes
  • 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.