Python 3 reference · String Methods

Python String count() Method

Return the number of non-overlapping occurrences of a substring, optionally only between start and end positions.

Python 3 Since 3.0

Syntax

str.count(sub, start=0, end=len(s))

Parameters

ParameterDescription
sub The substring to count.
start, end optional Only search this slice.

Return value

An int.

Examples

Count letters and substringsTry it yourself
text = "banana"
print(text.count("a"), text.count("an"), text.count("x"))

Output

3 2 0
Overlaps are not countedTry it yourself
print("aaaa".count("aa"))  # non-overlapping: 2, not 3

Output

2
Count from a positionTry it yourself
sentence = "the cat and the hat"
print(sentence.count("the"), sentence.count("the", 5))

Output

2 1

For counting every word or character at once, use collections.Counter.

Version history

VersionChange
Python 3.0Added