str.count()

Count how many times a substring occurs — non-overlapping, case-sensitive.

String methodPython 2.0+Live demo
Common call
"banana".count("an")
Returns
int — 0 when absent
Replaces
matches never overlap: "aaaa".count("aa") is 2, not 3
Watch out
case-sensitive; counting an empty sub returns len(s) + 1
str.count(subsubThe substring to count. Empty string counts the gaps: len(s) + 1.type: str · required, startstartSlice start, supports negative indexing.type: int · default: 0=0, endendSlice end (exclusive), supports negative indexing.type: int · default: len(s)=len(s))
int

Demo

Live evaluation
Try:
Inputs
stringstrthe source
substrto count
Output
'banana'.count('an')
2

Counting scans left to right and jumps past each match, so occurrences never overlap. The comparison is exact — case matters.

Parameters

NameTypeRequiredDescription
substryesThe substring to count. Empty string counts the gaps: len(s) + 1.
startintno (0)Slice start, supports negative indexing.
endintno (len(s))Slice end (exclusive), supports negative indexing.

Return value

intThe number of non-overlapping occurrences of sub in the (optionally sliced) string. Zero if not found.

Common patterns

Quick sanity checks
Count a delimiter before splitting on it.
if line.count(",") != 2:
    raise ValueError("expected 3 fields")
Character frequency
For a handful of characters count is fine; for full histograms use Counter.
vowels = sum(s.count(v) for v in "aeiou")

Examples

1. Count a substring
"banana".count("an")
Returns
2
2. Non-overlapping only
"aaaa".count("aa")
Returns
2
3. Absent substring
"hello".count("z")
Returns
0
4. Within a slice
"banana".count("a", 2)
Returns
2

Pitfalls

1. Overlapping matches are not counted
After a match, scanning resumes past it.
Expected 3?
"aaaa".count("aa")
2
Overlapping count
sum("aaaa".startswith("aa", i)
    for i in range(len("aaaa")))
3
2. Case-sensitive
Normalize first for case-insensitive counting.
Misses "A"
"Aa".count("a")
1
Fix
"Aa".lower().count("a")
2
3. Empty substring counts gaps
Every position between characters (plus both ends) matches the empty string.
Surprising
"abc".count("")
4
Guard
if sub:
    n = s.count(sub)
counted only when sub is non-empty

When to use

Use it
  • How many times does this literal substring occur
  • Validating an expected number of delimiters
  • Cheap containment-with-frequency checks
Reach for something else
  • Pattern counting → len(re.findall(...))
  • Full character histogram → collections.Counter
  • Just existence → "sub" in s (faster, clearer)

Notes

Complexity
O(n·m) worst case, fast in practice (CPython uses a tuned search)
Return
int
CPython impl
Objects/unicodeobject.c :: unicode_count
Memory
No allocation beyond the result
Thread-safe
Yes — str is immutable

FAQ

No. Lowercase both sides first, or use a regex with re.IGNORECASE.

s.lower().count(sub.lower())

History

2.0
Method available on the unified string type.