Content · Programming · Python

Python str.endswith Method: Usage and Examples

str.endswith(suffix, start, end) tests whether the selected portion of a string ends with a suffix. The suffix can also be a tuple of strings, which is useful for checking several file extensions. Learn with a clear.

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

This guide explains str.endswith Method: Usage and Examples through a focused example and practical reasoning. No prior knowledge of this specific operation is required.

Understanding the Concept


str.endswith(suffix, start, end) tests whether the selected portion of a string ends with a suffix. The suffix can also be a tuple of strings, which is useful for checking several file extensions.

When You Would Use This


Check whether a filename is one of the accepted text formats.

Step-by-Step Example


filename = "notes.TXT"
normalized_filename = filename.lower()
print(normalized_filename.endswith(".txt"))
print(normalized_filename.endswith((".txt", ".md")))

How the Example Works


Both checks return True. Normalizing the filename matters because suffix matching is case-sensitive. This is a filename test, not proof that the file content is safe or valid.

Example Output


True
True

Try It Yourself


Accept .csv and .tsv filename suffixes using a single call.

Common Beginner Mistakes


  • Forgetting that the comparison is case-sensitive.
  • Treating a filename extension as a reliable security or content-type check.
  • Assuming endswith() removes the suffix from the string.

Key Takeaways


  • str.endswith(suffix, start, end) tests whether the selected portion of a string ends with a suffix.
  • Both checks return True.
  • Avoid this mistake: Forgetting that the comparison is case-sensitive.
Share this resourceSend this page to someone who may find it useful.