search

str.count

Returns the number of non-overlapping occurrences of substring sub in [start:end]. Overlapping matches are not counted.

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

Parameters

Parameter Purpose
sub substring to count
start optional slice start
end optional slice end

Examples

>>> 'banana'.count('a')
3

counts every 'a'

>>> 'aaaa'.count('aa')
2

non-overlapping: 'aa' matches at 0 and 2, not 1

>>> 'hello'.count('z')
0

returns 0 when not found (no exception)

>>> 'abc'.count('')
4

empty substring counts as len(str)+1

Gotcha

Overlaps are ignored — 'aaaa'.count('aa') is 2, not 3. For overlapping counts use a regex with a lookahead.

Related methods

← All Python string methods · Python built-ins