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.
Python code
13 linesdef 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
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
- Use `os.path.splitext` to extract the extension and compare against a set.
- 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
More from Strings & text
- Automatically Detect Weak Passwords from Large Password Lists in Python easy
- Build CSV row from Python list with proper quoting easy
- Build a Secure Password Strength Checker in Python easy
- Convert Natural Language Dates to Datetime in Python medium
- Count Characters, Words, and Lines in Python Text easy
- Extract Data from Strings in Python: Beginner's Guide easy
Keep learning
Related tutorials and quizzes for this topic.