Home Python Bytes Methods find() Python bytes.find() Method Definition bytes.find() searches from the left and returns the index of the first match as an int. If sub does not occur, it returns -1 instead of raising an error.
Use it to locate a chunk name inside a file header, a separator in a network message, or a control byte in a frame. The needle may be bytes-like or a single int 0-255. If you only need a yes or no answer, the in operator is simpler; if a missing value is an error, use index() .
bytes.find() is a method of the built-in bytes type : call it on a bytes object with dot notation, such as data.find(...). No import is needed, and bytearray objects have the same method.
Syntax Search the whole object, or only the slice between start and end.
pos = data.find(sub)
pos = data.find(sub, start)
pos = data.find(sub, start, end) Call What it does b"key=value".find(b"=")Returns 3. b"key=value".find(b"#")Returns -1: not found. b"\x01\x02\x01".find(1, 1)Returns 2: search starts at index 1. b"abc".find(b"")Returns 0: an empty needle matches at the start.
The returned index always refers to the whole object, even when you pass start.
Method signatures bytes.find(sub[, start[, end]])
# sub: bytes-like object or int in range(256)
# returns -1 when sub is not found Parameters Parameter Description sub The bytes to look for, or one byte value as an int 0-255. start Optional. Index to start searching from. Negative values count from the end. end Optional. Index to stop before. The whole match must fit before end.
Return Value Return Value Description int The lowest index where sub starts. -1 Returned when sub is not found in data[start:end].
Important
Because -1 is also a valid slice index, never slice with the result before checking it: data[data.find(b":"):] silently returns the last byte when the colon is missing. A str needle raises TypeError, and an int outside 0-255 raises ValueError.
Python Examples 1. Find markers in a PNG header 2. Slice a header value 3. Find a control byte Example 1 — Locate Markers in a PNG File Header The first bytes of a PNG file contain a fixed signature followed by the first chunk name, IHDR. find() reports where each marker sits.
header = b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR"
print(header.find(b"PNG"))
print(header.find(b"IHDR"))
print(header.find(b"JFIF"))
print(header.find(b"\r\n")) How It Works After the high byte. The signature starts with \x89, so the letters PNG begin at index 1.Chunk name offset. Eight signature bytes plus a four-byte length put IHDR at index 12.Wrong format. JFIF belongs to JPEG files, so this header returns -1.First match only. The header holds \r\n at index 4 and a lone \r at index 11, but only index 4 is the two-byte pair.Example 2 — Extract a Header Value from an HTTP Request Combine two find() calls: one for the field name and one for the line ending that follows it, starting the second search where the value begins.
request = b"Host: example.com\r\nUser-Agent: demo\r\n"
start = request.find(b"Host: ") + len(b"Host: ")
end = request.find(b"\r\n", start)
print(start, end)
print(request[start:end])
print(request.find(b"\r\n", end + 2)) How It Works Skip the label. The field name is found at 0; adding its length (6) gives the first byte of the value.Search from an offset. Passing start makes find() ignore everything before the value, so it returns the first line ending after it, at 17.Slice the value. request[6:17] is exactly the host name as bytes.Next line. Starting at end + 2 skips the current \r\n and finds the end of the User-Agent line at 35.Example 3 — Find Control Bytes in a Framed Message Serial protocols often wrap data between STX (0x02) and ETX (0x03) bytes. Search for those values as ints and limit a search with end.
frame = b"\x02DATA\x03\x02MORE\x03"
print(frame.find(3))
print(frame.find(0x02, 1))
print(frame.find(b"MORE", 0, 8))
print(b"DATA" in frame, 0x7f in frame) How It Works End of the first frame. The int 3 matches the ETX byte right after DATA, at index 5.Skip the first STX. Starting at index 1 jumps over the opening 0x02 and finds the second one at 6.Must fit before end. MORE occupies indexes 7 to 10, so it does not fit in the range ending at 8 and the result is -1.Membership tests. in accepts both a bytes needle and an int; the DEL byte 0x7f is absent.Frequently Asked Questions What does bytes.find() return when nothing is found? It returns -1. Check for it before slicing, because -1 is also a valid index meaning the last byte.
What is the difference between find() and index()? They return the same index when the needle exists. When it does not, find() returns -1 and index() raises ValueError.
Can I search for a single byte value? Yes. Pass an int from 0 to 255, for example data.find(0) finds the first zero byte.
How do I find the last occurrence? Use rfind(), which searches from the right and also returns -1 when the needle is missing.
Does find() accept a str? No. bytes.find("x") raises TypeError. Use b"x", or encode the text with the same encoding as the data.
Next: bytes.fromhex() Class method: build bytes from a string of hex digits.
fromhex() → About the author Developer, cloud engineer, and technical writer
I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.
13 people found this page helpful
Helpful Share Copy link Suggestion