How to Check if a String Ends with a File Extension in Python

This code checks whether a filename ends with any of a list of file extensions, handling case insensitivity.

Easy Python 3.9+ Aug 9, 2026 Strings & text 17 views 0 copies

Python code

13 lines
Python 3.9+
def ends_with_extension(filename, extensions):
    """Check if a filename ends with any of the given extensions."""
    lower_name = filename.lower()
    return any(lower_name.endswith(ext.lower()) for ext in extensions)

if __name__ == "__main__":
    # Test cases
    test_files = ["report.pdf", "image.PNG", "script.py", "notes.txt", "archive.tar.gz"]
    extensions = [".pdf", ".png", ".py"]
    
    for file in test_files:
        result = ends_with_extension(file, extensions)
        print(f"{file:20} -> {result}")

Output

stdout
report.pdf          -> True
image.PNG          -> True
script.py          -> True
notes.txt          -> False
archive.tar.gz     -> False

How it works

The endswith method checks if a string ends with a specified suffix. By converting both the filename and each extension to lowercase using .lower(), the check becomes case-insensitive. The any() function returns True if at least one extension matches, otherwise False. This approach is simple and efficient for a small list of extensions.

Common mistakes

  • Forgetting to convert both filename and extension to lowercase, causing case-sensitive mismatches.
  • Not including the leading dot in extensions (e.g., using 'pdf' instead of '.pdf').
  • Checking only one extension with `endswith` instead of iterating over a list.

Variations

  1. Use `os.path.splitext` to extract the extension and compare against a set.
  2. Use a regular expression to match a pattern of allowed extensions.

Real-world use cases

  • Filtering uploaded files in a web application to only allow certain file types.
  • Validating file extensions before processing in a batch data pipeline.
  • Checking downloaded files to ensure they have the expected format before parsing.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Strings & text

Related tutorials and quizzes for this topic.