Python String count() Method

Short answer
str.count(sub) returns how many non-overlapping times sub appears in a string. It returns 0 when there is no match and never raises an error for a missing substring.

count() is the quickest way to answer questions such as "how many commas are in this line?" or "how often does a word appear in this sentence?". It scans the string once and gives back an int. If you also need the positions of the matches, look at index() or find(); if the thing you are counting lives in a list, the list has its own count() method.

Quick facts
Syntaxtext.count(sub, start, end)
Parameterssub: substring to count; start, end (optional): count only inside text[start:end]
ReturnsNumber of non-overlapping matches (int, 0 if none)
Case sensitiveYes
Overlapping matchesNot counted: "aaaa".count("aa") is 2

How str.count() counts matches

Python looks for sub from the left. After each match it continues after the end of that match, which is why matches never overlap.

Python
print("banana".count("a"))
print("banana".count("an"))
print("aaaa".count("aa"))

The third line prints 2, not 3: the first match uses characters 0-1 and the second uses characters 2-3.

Counting with start and end positions

Passing start and end limits the count to text[start:end], using the same rules as string slicing. The slice itself is not created, so this is cheap even for long strings.

Python
row = "a,b,c,d"
print(row.count(","))
print(row.count(",", 3))
print(row.count(",", 0, 4))

Counting without worrying about case

Because count() is case sensitive, "Apple apple".count("apple") is 1. Normalise the text first with lower() so that every spelling counts. The same trick works for comparing strings while ignoring case.

Special cases and alternatives

GoalCodeResult for the sample
Count one character"hello".count("l")2
Count a word as plain text"the cat and the hat".count("the")2
Count whole words only"the then".split().count("the")1
Count an empty string"abc".count("")4 (len + 1)
Count a missing text"abc".count("z")0
Count overlapping matchessum(s[i:].startswith("aa") for i in range(len(s))) with s = "aaaa"3

Examples you can run

Press Run, then edit the code and run it again.

Count characters in a sentence

The basic use: count one letter and one word inside a sentence.

Count characters in a sentence
text = "the cat and the hat"
print(text.count("a"))
print(text.count("the"))
print(text.count("dog"))
Expected output3
2
0

Count a word ignoring case

Lower-casing first makes all spellings match. Compare this with the plain call.

Count a word ignoring case
review = "Great phone. GREAT battery. great price."
print(review.count("great"))
print(review.lower().count("great"))
Expected output1
3

Count lines and columns in CSV text

Counting newline characters and commas tells you the shape of a small CSV block without parsing it.

Count lines and columns in CSV text
data = "name,score\nAsha,90\nRavi,85\nMeena,78"
print(data.count("\n") + 1)
print(data.splitlines()[0].count(",") + 1)
Expected output4
2

Count whole words instead of substrings

count("is") also matches inside this. Splitting into words first counts only the real word.

Count whole words instead of substrings
text = "this is it"
print(text.count("is"))
print(text.split().count("is"))
Expected output2
1

Common mistakes

Passing a non-string argument

✗ Wrong

code = "a1b1"
print(code.count(1))
TypeError: must be str, not int

✓ Right

code = "a1b1"
print(code.count(str(1)))

count() searches for text, so convert the number with str() first.

Expecting overlapping matches to be counted

✗ Wrong

print("aaaa".count("aa"))  # expecting 3
Prints 2, because matches cannot overlap.

✓ Right

s = "aaaa"
print(sum(s.startswith("aa", i) for i in range(len(s))))

Use a loop with startswith() or a regular expression with a lookahead when overlaps matter; see Python regex.

Counting words with a substring match

✗ Wrong

print("the other day".count("the"))  # expecting 1
Prints 2, because `the` is also inside `other`.

✓ Right

print("the other day".split().count("the"))

Split the string into words and count in the list.

Python String count() Method: questions people ask

How do I count occurrences of a character in a string in Python?

Call text.count("x"), replacing x with the character. It returns 0 if the character does not appear.

Does Python string count() overlap matches?

No. After a match, counting continues after its end, so "aaaa".count("aa") is 2.

Is str.count() case sensitive?

Yes. Convert the string with lower() or upper() before counting when you want to ignore case.

Keep learning

Step-by-step lessons:
Python StringsPython String Methods

Related:
Python String find() MethodPython String index() MethodHow to Split a String into Words in PythonHow to Compare Strings Ignoring Case in PythonPython String lower() Method

More in string methods:
Python String split() MethodPython String join() MethodPython String strip() MethodPython String lstrip() MethodPython String rstrip() MethodPython String replace() MethodPython String upper() MethodPython String lower() Method See all →