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.
print("report.pdf".endswith(".pdf")) # True
Try it
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.
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
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
"", sos.endswith("")isTrue. An empty tuple is alwaysFalse. - Bounds act as a slice.
s.endswith(x, start, end)tests whethers[start:end]ends withx. - 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").suffixor.suffixesunderstands extensions better than raw string tests. - Works on bytes too, with bytes arguments.