Skip to content

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.

Beginner 8 min read·Lesson 99 of 306 in Python Programming

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

Python
if name.lower().endswith((".jpg", ".png")):
pass
base = name.removesuffix(".txt")
  • Returns True or False.
  • Use a tuple for several suffixes.
  • Lower-case first for extensions.

Code examples

Checking endings

Python
print("notes.txt".endswith(".txt"))
print("Is it ready?".endswith("?"))
print("PHOTO.JPG".endswith(".jpg"))
print("PHOTO.JPG".lower().endswith(".jpg"))
Output
True
True
False
True

Several suffixes and removing one

Python
for f in ["cat.png", "doc.pdf", "pic.jpeg"]:
print(f, f.endswith((".png", ".jpg", ".jpeg")))
print("draft_v2.txt".removesuffix(".txt"))
Output
cat.png True
doc.pdf False
pic.jpeg True
draft_v2

More examples

Sorting uploads by type

Python
uploads = ["Results.CSV", "photo.JPG", "notes.txt", "scan.pdf", "data.json", "logo.png"]
buckets = {"data": [], "images": [], "documents": [], "other": []}
for name in uploads:
lower = name.lower()
if lower.endswith((".csv", ".json")):
buckets["data"].append(name)
elif lower.endswith((".jpg", ".jpeg", ".png")):
buckets["images"].append(name)
elif lower.endswith((".pdf", ".txt")):
buckets["documents"].append(name)
else:
buckets["other"].append(name)
for kind, files in buckets.items():
print(f"{kind:<10} {files}")
Output
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:

TextOutput
data ['Results.CSV', 'data.json']
images ['photo.JPG', 'logo.png']
documents ['notes.txt', 'scan.pdf']
other []

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

name.endswith(".pdf") # misses .PDF

Prefer

name.lower().endswith(".pdf")

Extensions often appear in upper case.

Checking “pdf” without the dot

Avoid

name.endswith("pdf") # matches "notapdf"

Prefer

name.endswith(".pdf")

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

  1. 1
    Print whether a sentence ends with ., ! or ?.
  2. 2
    From 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?
Practise this topic