Python Glossary Русский

all Python 3Strings (str)function

str.count

search

Return the number of non-overlapping occurrences of the substring.

Syntax

s.count(sub[, start[, end]])

Matches are counted left to right and never overlap, so 'aa' occurs twice in a run of four 'a' characters, not three times. An empty substring returns len(s)+1, one position between every pair of characters plus both ends. Each call rescans the whole string, so tallying many different characters with many count calls is wasteful — collections.Counter does it in a single pass.

Examples

print('banana'.count('a'))   # → 3
print('banana'.count('na'))  # → 2
print('aaa'.count('aa'))     # → 1

See also

Open in the full glossarydocs.python.orgReport an inaccuracy