Module 7 · Strings — topic 18 of 22
endswith()
endswith(suffix) checks how a string ends. Use it for file extensions, punctuation and domains, with tuples for several suffixes and lower() for case-insensitive checks.
Learning objectives
- Test suffixes with endswith()
- Check file extensions robustly
- Combine endswith() with removesuffix()
Definition
endswith(suffix) checks how a string ends. Use it for file extensions, punctuation and domains, with tuples for several suffixes and lower() for case-insensitive checks.
Introduction
endswith(suffix) returns True if the string ends with suffix. It mirrors startswith() and is the standard way to check file extensions, domain names and sentence endings.
Why it matters
Programs often decide what to do with text or files by their ending: .csv files go to the data importer, .jpg files to the image viewer, addresses ending in @company.com get internal access.
Detailed explanation
Ending checks are cheap: Python compares only the last few characters, however long the string is.
Checking endings with endswith() avoids fragile slicing such as name[-4:] == ".pdf", which silently breaks for longer extensions like .docx or .jpeg. The method states the intent directly and adapts to any suffix length.
Suffix checks are a quick first filter, not a guarantee. A file called photo.jpg could actually contain text, and an email ending in a company domain still needs verification. Use endswith() to route or reject obvious cases early, and rely on deeper checks where security or correctness matters.
Like startswith(), endswith() works well with any() and comprehensions. [f for f in files if f.lower().endswith(".csv")] selects every CSV file from a list in one line.
Remember that some extensions have two parts, such as .tar.gz. endswith(".gz") matches them, while rsplit(".", 1) would only return gz as the extension.
endswith(suffix) compares the end of the string exactly and is case-sensitive.
Pass a tuple to accept several suffixes: name.endswith((".jpg", ".jpeg", ".png")).
Optional start and end arguments limit the part of the string being checked.
File extensions vary in case (.PDF and .pdf), so lower-case the name before checking.
removesuffix(suffix) returns the string without the suffix if it is present, and unchanged otherwise.
For real file paths, pathlib’s Path(name).suffix (Module 13) is even more robust.
Syntax
- Returns True or False.
- Use a tuple for several suffixes.
- Lower-case first for extensions.
Code examples
Checking endings
True True False True
Several suffixes and removing one
cat.png True doc.pdf False pic.jpeg True draft_v2
More examples
Sorting uploads by type
data ['Results.CSV', 'data.json'] images ['photo.JPG', 'logo.png'] documents ['notes.txt', 'scan.pdf'] other []
Step-by-step explanation
- Each name is lower-cased once so extensions match in any case.
- Tuples of suffixes group related file types.
- The original names are stored, preserving their capitalisation.
- Unknown types would land in other; here every file was recognised.
Expected output
Running “Sorting uploads by type” prints exactly:
Practical applications
- Upload handlers accept or reject files by extension.
- Email filters route messages by the sender’s domain ending.
- Grammar checkers look at sentence endings.
Best practices
- Include the dot in extension checks.
- Lower-case before comparing.
- Use pathlib for full path handling.
Common mistakes
Case-sensitive extension checks
Avoid
Prefer
Extensions often appear in upper case.
Checking “pdf” without the dot
Avoid
Prefer
Include the dot so only real extensions match.
Key takeaways
- endswith(suffix) tests how a string ends.
- Tuples check several suffixes; matching is case-sensitive.
- removesuffix removes an exact ending.
Try it yourself
- 1Print whether a sentence ends with ., ! or ?.
- 2From a list of emails, print those ending with "@gmail.com", ignoring case.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
1 question test this exact topic. Answers and explanations are revealed after you submit.
- BeginnerWhat is printed?