bytes.endswith() returns True if the bytes end with suffix, or with any suffix in a tuple, and False otherwise.
Typical uses: telling CRLF (b"\r\n") from LF (b"\n") line endings, checking that a message carries its terminator, and filtering file names returned as bytes by their extension. start and end narrow the check to a slice, for example to ignore a trailing checksum byte.
bytes.endswith() is a method of the built-in bytes type: call it on a bytes object with dot notation, such as data.endswith(...). No import is needed, and bytearray objects have the same method.
Syntax
Pass a suffix or a tuple of suffixes, plus an optional range.
python
ok = data.endswith(suffix)
ok = data.endswith((suffix1, suffix2))
ok = data.endswith(suffix, start, end)
Call
What it does
b"line\r\n".endswith(b"\r\n")
Returns True.
b"a.mp3".endswith((b".mp3", b".ogg"))
Returns True.
b"END!".endswith(b"END", 0, 3)
Returns True: only b"END" is checked.
b"abc".endswith(b"C")
Returns False: matching is case-sensitive.
Like startswith(), the suffix must be bytes-like or a tuple of bytes-like objects; an int is not accepted.
Method signatures
python
bytes.endswith(suffix[, start[, end]])
# suffix: bytes-like object or tuple of bytes-like objects
Parameters
Parameter
Description
suffix
A bytes-like object, or a tuple of them.
start
Optional. Index where the checked slice begins.
end
Optional. Index where the checked slice ends; the suffix must end right before it.
Return Value
Return Value
Description
True
data[start:end] ends with the suffix (or one of the tuple items).
False
It does not.
Python Examples
Example 1 — Tell CRLF, LF, and Missing Line Endings Apart
Lines read from a file opened in binary mode keep their line endings. Check the longer ending first so CRLF lines are not reported as LF.
python
lines = [b"alpha\r\n", b"beta\n", b"gamma"]
for raw in lines:
if raw.endswith(b"\r\n"):
print(raw, "CRLF")
elif raw.endswith(b"\n"):
print(raw, "LF")
else:
print(raw, "no newline")
Output
b'alpha\r\n' CRLF
b'beta\n' LF
b'gamma' no newline
How It Works
Longest first.b"alpha\r\n" also ends with b"\n", so the CRLF test must come before the LF test.
Unix ending.b"beta\n" fails the first test and passes the second.
Last line. The final line of a file often has no newline at all, which the else branch reports.
Example 2 — Filter Media Files by Extension
File names can arrive as bytes, for example from os.listdir(b"."). A tuple checks several extensions, and lowering first ignores case.
python
names = [b"song.mp3", b"clip.MP4", b"notes.txt", b"movie.mkv"]
media = (b".mp3", b".mp4", b".mkv")
for name in names:
print(name, name.endswith(media), name.lower().endswith(media))