str.count
Count the non-overlapping occurrences of the substring sub.
Python 3.13
str.count(sub[, start[, end]])- [ ]optional part
- sub
- The substring to count.str
- start
- The index to start searching from, 0 by default; a negative one counts from the end.intOptional
- end
- The index before which the search stops, the end by default; a negative one counts from the end.intOptional
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.
