str.endswith()

Does the string end with this suffix? The file-extension check, done right.

String methodPython 2.0+Live demo
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(suffixsuffixThe suffix to test — or a tuple of suffixes, any of which may match.type: str | tuple[str] · required, startstartTest within the slice starting here.type: int · default: 0=0, endendTest 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

NameTypeRequiredDescription
suffixstr | tuple[str]yesThe suffix to test — or a tuple of suffixes, any of which may match.
startintno (0)Test within the slice starting here.
endintno (len(s))Test as if the string ended here (exclusive).

Return value

boolTrue 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
True
2. No match
"report.pdf".endswith(".doc")
Returns
False
3. Tuple of suffixes
"photo.png".endswith((".jpg", ".png"))
Returns
True
4. Empty suffix
"abc".endswith("")
Returns
True

Pitfalls

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.