Python Glossary Русский

all Python 3Byte sequencesfunction

bytes.count

bytes — search

Count non-overlapping occurrences of a subsequence.

Syntax

b.count(...)

Matches are counted without overlap: after a hit the scan resumes right past it, so self-overlapping patterns yield fewer counts than a naive reading suggests. The argument may be any bytes-like object or an integer in range 0-255 (a single byte), but never a str — that raises TypeError. An empty subsequence matches in every gap and returns len(b) + 1.

Examples

print(b'banana'.count(b'a'))   # → 3
print(b'banana'.count(b'an'))   # → 2
print(b'aaaa'.count(b'aa'))   # → 2
print(b'banana'.count(b'a', 2))   # → 2
print(b'banana'.count(97))   # → 3
print(b'abc'.count(b''))   # → 4

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy