bytes.endswith()
The mirror of startswith. Most useful for terminators and trailers — checking a message ended cleanly, or that a file carries its expected footer.
Demo
A suffix test, byte for byte, returning True or False. The same two edge cases as startswith apply: an empty suffix is always True, and a suffix longer than the data is False rather than an error. Because it compares in place it is both faster and safer than negative slicing, which misbehaves when the suffix is empty.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| suffix | bytes | tuple | yes | Bytes to test for, or a TUPLE of alternatives. A list raises TypeError. |
| start | int | no (0) | Byte offset to treat as the beginning of the region tested. |
| end | int | no (len) | Byte offset to treat as the END — the suffix is matched here, not at the real end. |
Return value
bool — True if the buffer ends with suffix. A tuple of suffixes returns True if ANY of them match.
Common patterns
if buffer.endswith(b'\r\n'): dispatch(buffer)
if path_bytes.endswith((b'.jpg', b'.jpeg', b'.png')): handle_image()
if data.endswith(ZIP_EOCD_MAGIC): ...
Examples
Pitfalls
s = b'' b'abc'[-len(s):] == s
b'abc'.endswith(b'')
b'abc'.endswith([b'c'])
b'abc'.endswith(tuple(suffixes))
b'abcdef'.endswith(b'ef', 0, 4)
b'abcdef'.endswith(b'cd', 0, 4)
b'a.png'.endswith('.png')
b'a.png'.endswith(b'.png')
When to use
- Confirming a message or frame terminator
- Matching one of several file extensions with the tuple form
- Verifying a trailing signature or footer
- The match could be anywhere → rfind or the in operator
- The data is text → decode first and use str.endswith
- Removing the suffix → removesuffix does the test and the trim together
Notes
FAQ
Because data[-len(suffix):] breaks when the suffix is empty: -0 is 0, so the slice is the entire buffer and the comparison fails. endswith handles that correctly and avoids the allocation too.
b'abc'.endswith(b'') # True b'abc'[-0:] == b'' # False