String method

str.count()

Counts how many times a piece of text appears in a string, without overlaps, in the whole string or in a part of it.

BeginnerEvery example below runs in your browser. Change the code and press Run.

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

count() tells you how many times sub appears in a string. It is case-sensitive and counts exact text, so "a" and "A" are different.

Use it to count letters, words, commas in a CSV line, or new lines in a text.

Two details surprise people. Matches do not overlap: "aaaa".count("aa") is 2, not 3. And count() finds text inside longer words, so counting "the" also counts the the in "theory".

Parameters

ParameterWhat it is
sub
required
The text to count.
start
optional, default 0
Where to begin counting.
end
optional, default len(str)
Where to stop counting.

Return value

The number of matches, as an int (0 if there are none).

Examples

1Count a letter

Pythoneditable
word = "banana"
print(word.count("a"))
print(word.count("an"))
print(word.count("z"))
Output
3
2
0

2Count values in a CSV line

There is always one more value than there are commas.

Pythoneditable
line = "Ana,Omar,Yuki,Lena"
print(line.count(",") + 1, "names")
Output
4 names

3Count whole words, not pieces of words

Pythoneditable
sentence = "the theory of the other"
print(sentence.count("the"))
print(sentence.split().count("the"))
Output
4
2

The first line also counts the inside theory and other. Splitting into words and using list.count() counts whole words only.

4Count vowels

Pythoneditable
text = "programming in python"
vowels = sum(text.count(v) for v in "aeiou")
print(vowels)
Output
5

5Matches do not overlap

Pythoneditable
print("aaaa".count("aa"))
print("abababa".count("aba"))
Output
2
2

Common mistakes

Forgetting about upper and lower case

count() treats "P" and "p" as different letters. Lower-case the text first.

Pythoneditable
text = "Python is popular"
print(text.count("p"))
print(text.lower().count("p"))
Output
2
3

Questions people ask

How do I count all letters at once?

Use collections.Counter(text): it counts every character in one pass.

How do I count words in a string?

len(text.split()) counts all words; text.split().count("word") counts one word.

Why does "abc".count("") give 4?

The empty string is found between every character and at both ends: 3 letters give 4 places.

Can count() count overlapping matches?

No. For overlapping matches, use a loop with str.find(), moving one position after each match.

Spotted a mistake on this page? Tell us