Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท String Methods

Python str.endswith() method

Reference for Python str.endswith(): test whether a string ends with a suffix or any suffix from a tuple, with start and end bounds and common mistakes.

The str.endswith() method returns True if a string ends with the given suffix and False otherwise. The suffix can also be a tuple of suffixes, in which case the result is True when the string ends with any of them.

It is the standard way to check file extensions, URL endings and similar patterns, and it is clearer and safer than slicing the end of the string by hand.

Python
print("report.pdf".endswith(".pdf"))   # True

Try it

Python Checking suffixes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Bounds and the list mistake

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
str.endswith(suffix)
str.endswith(suffix, start)
str.endswith(suffix, start, end)
Name Description
suffix A string, or a tuple of strings, to look for at the end.
start Optional. Index at which to start looking (default 0).
end Optional. Index at which to stop looking, exclusive (default len(s)).

Return value: True or False.

Raises: TypeError if suffix is not a string or a tuple of strings (a list or set is rejected).

Usage notes

  • Case-sensitive. Lower-case the string first for a caseless test, as in name.lower().endswith(".jpg").
  • Tuple, not list. Several suffixes need a tuple. Convert a list with tuple(items).
  • Empty suffix. Every string ends with "", so s.endswith("") is True. An empty tuple is always False.
  • Bounds act as a slice. s.endswith(x, start, end) tests whether s[start:end] ends with x.
  • Prefer it over slicing. s[-4:] == ".pdf" breaks silently if you miscount; endswith(".pdf") states intent.
  • Remove a suffix with removesuffix() (Python 3.9+) after testing, or in one step, since it does nothing when the suffix is absent.
  • For paths, pathlib.Path("a/b.tar.gz").suffix or .suffixes understands extensions better than raw string tests.
  • Works on bytes too, with bytes arguments.