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.
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
| Parameter | What it is |
|---|---|
subrequired | The text to count. |
startoptional, default 0 | Where to begin counting. |
endoptional, 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
word = "banana"
print(word.count("a"))
print(word.count("an"))
print(word.count("z"))3 2 0
2Count values in a CSV line
There is always one more value than there are commas.
line = "Ana,Omar,Yuki,Lena"
print(line.count(",") + 1, "names")4 names
3Count whole words, not pieces of words
sentence = "the theory of the other"
print(sentence.count("the"))
print(sentence.split().count("the"))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
text = "programming in python"
vowels = sum(text.count(v) for v in "aeiou")
print(vowels)5
5Matches do not overlap
print("aaaa".count("aa"))
print("abababa".count("aba"))2 2
Common mistakes
Forgetting about upper and lower case
count() treats "P" and "p" as different letters. Lower-case the text first.
text = "Python is popular"
print(text.count("p"))
print(text.lower().count("p"))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.