Python Function Reference

str.count

Count the non-overlapping occurrences of the substring sub.

Python 3.13
str.count(sub[, start[, end]])

Parameters

substr
The substring to count.
startintoptional
The index where the search starts.
endintoptional
The index before which the search stops.

Return value

An integer; 0 if the substring is not found.

Examples

Counting a letter in a word

Python 3.13
print('banana'.count('a'))
3

Matches do not overlap

Python 3.13
print('aaaa'.count('aa'))
2

Details

Unlike list.count, it looks for a substring rather than a single item. Overlapping occurrences are not counted: "aa" occurs in "aaaa" 2 times.

See also

Where to learn