str.endswith()
Does the string end with this suffix? The file-extension check, done right.
Common call
name.endswith(".py")
Returns
bool
Replaces
accepts a tuple: name.endswith((".jpg", ".png"))
Watch out
case-sensitive — ".JPG" is not ".jpg"
str.endswith(suffixsuffix — The suffix to test — or a tuple of suffixes, any of which may match.type: str | tuple[str] · required, startstart — Test within the slice starting here.type: int · default: 0=0, endend — Test as if the string ended here (exclusive).type: int · default: len(s)=len(s))
→ bool
Demo
Live evaluation
Try:
Inputs
stringstrthe source
suffixstrthe suffix
Output
'report.pdf'.endswith('.pdf')
True
The mirror of startswith: an exact, case-sensitive check at the end of the string. The empty suffix matches everything.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| suffix | str | tuple[str] | yes | The suffix to test — or a tuple of suffixes, any of which may match. |
| start | int | no (0) | Test within the slice starting here. |
| end | int | no (len(s)) | Test as if the string ended here (exclusive). |
Return value
bool — True when the (optionally sliced) string ends with suffix. Also accepts a tuple of suffixes — True if any matches.
Common patterns
File-extension filter
The tuple form covers several extensions in one call.
images = [f for f in files if f.lower().endswith((".jpg", ".png", ".gif"))]
Trailing punctuation checks
Normalize sentence ends before further processing.
if not line.endswith("."): line += "."
Examples
1. Basic suffix test
"report.pdf".endswith(".pdf")
Returns
True2. No match
"report.pdf".endswith(".doc")
Returns
False3. Tuple of suffixes
"photo.png".endswith((".jpg", ".png"))
Returns
True4. Empty suffix
"abc".endswith("")
Returns
TruePitfalls
1. Case-sensitive
Real-world filenames mix cases — normalize first.
Misses
"IMG.JPG".endswith(".jpg")
False
Fix
"IMG.JPG".lower().endswith(".jpg")
True
2. A list of suffixes raises
The multi-suffix form requires a tuple specifically.
Raises
f.endswith([".jpg", ".png"])
TypeError: endswith first arg must be str or a tuple of str
Fix
f.endswith((".jpg", ".png"))
works — tuple, not list
When to use
Use it
- File-extension checks
- Any suffix test — clearer than s[-n:] slicing
- Several acceptable suffixes → the tuple form
Reach for something else
- Remove the suffix too → str.removesuffix
- Real path handling → pathlib.Path.suffix
- Prefix instead → str.startswith
Notes
Complexity
O(len(suffix))
Return
bool
CPython impl
Objects/unicodeobject.c :: unicode_endswith
Memory
No allocation
Thread-safe
Yes — str is immutable
FAQ
For real paths use pathlib; for quick string work, rsplit or rfind.
from pathlib import Path Path("a/report.pdf").suffix # '.pdf'
History
2.5
Tuple-of-suffixes form added.
2.0
Method available on the unified string type.