bytes.count()
The bytes twin of str.count. Same counting rules — including the non-overlapping one — but it counts BYTES, and it rejects a str argument outright.
Demo
Counting works exactly as it does on strings, with two byte-level twists. Matches do not overlap: "aaa" contains "aa" only once, because the scan resumes after each match rather than one position later. And the empty sequence is found at every gap, giving length plus one. The non-ascii case counts a two-byte UTF-8 sequence as a single match, because both the data and the argument were encoded the same way.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| sub | bytes | int | yes | Byte sequence to count. A plain int from 0 to 255 also works, counting that single byte value. |
| start | int | no (0) | Byte offset to begin at. |
| end | int | no (len) | Byte offset to stop at, exclusive. |
Return value
int — Number of non-overlapping occurrences of sub. Returns 0 when absent, never raises.
Common patterns
record_count = payload.count(b'\n')
if data.count(b'\x00') > MAX_NULLS: raise ValueError('looks corrupt')
zeros = data.count(0)
Examples
Pitfalls
b'abc'.count('a')
b'abc'.count(b'a')
b'aaa'.count(b'aa')
sum(1 for i in range(len(d)-1) if d[i:i+2] == b'aa')
len('héllo'.encode())
'héllo'.encode().decode().count('l')
When to use
- Counting delimiters or markers in a binary buffer
- Cheap validation before parsing a format
- Counting a single byte value with an int argument
- The data is text → decode first and count characters
- Overlapping matches → a manual loop or a lookahead regex
- You want the POSITION → find or index
Notes
FAQ
Because Python refuses to guess an encoding. Counting b'é' means counting two specific bytes, and which two depends on the codec — so you must encode the argument yourself and make that choice explicit.
data.count('é'.encode('utf-8'))