The count() method returns how many times a substring appears in a string. It is case-sensitive, counts non-overlapping matches, and optionally lets you limit the search to a slice using start and end. It is one of the most useful methods for quick text analysis in Python.
01
Occurrences
Count how many times sub appears.
02
Syntax
sub, start, and end params.
03
Case-Sensitive
Uppercase ≠ lowercase.
04
Slice Search
Limit range with start/end.
05
Characters
Count single letters too.
06
vs find()
Frequency vs first index.
Fundamentals
Definition and Usage
In Python, count() is a built-in string method that scans a string for a substring and returns the number of times it occurs without overlapping. For example, "banana".count("ana") returns 1, not 2, because the two possible "ana" spans share the middle "a".
💡
Beginner Tip
If you only need to know whether a substring exists, use sub in string or find(). Use count() when you need the number of occurrences—word frequency, character totals, or validation checks.
Foundation
📝 Syntax
The count() method accepts one required and two optional parameters:
python
string.count(sub, start, end)
Syntax Rules
sub — the substring to search for (required).
start — optional start index; search begins here (default 0).
end — optional end index; search stops before this position (default end of string).
Return value — a non-negative int; returns 0 when sub is not found.
Empty sub — passing an empty string raises ValueError.
Cheat Sheet
⚡ Quick Reference
Expression
Result
"hello hello".count("hello")
2
"banana".count("ana")
1 (non-overlapping)
"Python".count("python")
0 (case-sensitive)
"abracadabra".count("a")
5
"mississippi".count("ss", 2, 7)
1 (slice only)
Basic
text.count("python")
Count word occurrences
Character
text.count("a")
Count one letter
Slice
text.count("is", 0, 10)
Search within range
Missing
text.count("Java")
Returns 0 if absent
Hands-On
Examples Gallery
Run these examples in any Python 3 interpreter. Each one shows a common counting pattern.
📚 Getting Started
Count how many times a word appears in a sentence.
Example 1 — Basic count()
Count occurrences of the word "python" in a longer string.
python
text = "python is powerful, python is easy, python is fun"
word = "python"
total = text.count(word)
print(f"'{word}' appears {total} times.")
📤 Output:
'python' appears 3 times.
How It Works
count() scans the string from left to right.
Each match is counted once; the search continues after the matched substring.
The original string is not modified—only an integer is returned.
Example 2 — Counting Characters
Count how many vowels appear in a sentence by counting each letter separately.
python
text = "programming is interesting"
vowels = "aeiou"
total = sum(text.count(v) for v in vowels)
print("Vowel count:", total)
📤 Output:
Vowel count: 8
How It Works
count() works on single characters too. Summing counts for each vowel gives the total vowel occurrences in the text.
📈 Practical Patterns
Slice limits, case rules, and overlapping behavior in real scenarios.
Example 3 — Using start and end
Search only within part of the string by passing slice boundaries.
python
text = "mississippi"
full = text.count("ss")
partial = text.count("ss", 2, 7)
print("Full string:", full)
print("Index 2–7: ", partial)
📤 Output:
Full string: 2
Index 2–7: 1
How It Works
text.count("ss", 2, 7) only searches inside text[2:7], which is "sissi". One "ss" appears there, while the full string has two.
Example 4 — Case Sensitivity
count() treats uppercase and lowercase as different characters.
python
sentence = "This is a simple sentence. Is it simple?"
lower_count = sentence.count("simple")
mixed_count = sentence.count("Simple")
print("'simple':", lower_count)
print("'Simple':", mixed_count)
📤 Output:
'simple': 2
'Simple': 0
How It Works
Both occurrences use lowercase "simple". The capitalized form does not match. For case-insensitive counting, fold both strings with casefold() first.
Example 5 — Non-Overlapping Matches
Understand why count() does not count overlapping substrings.
python
text = "aaa"
sub = "aa"
print("Text: ", repr(text))
print("Sub: ", repr(sub))
print("Count:", text.count(sub))
📤 Output:
Text: 'aaa'
Sub: 'aa'
Count: 1
How It Works
Visually: aaa — one match at index 0. The second possible "aa" at index 1 overlaps the first, so it is not counted. For overlapping patterns, use regular expressions.
Applications
🚀 Common Use Cases
Word frequency — count how often a keyword appears in a paragraph or log file.
Character analysis — tally letters, digits, or symbols in user input.
Validation — check that a delimiter or marker appears the expected number of times.
Substring presence — use count(sub) > 0 as a simple existence check.
Partial search — limit counting to a slice when processing part of a document.
🧠 How count() Works
1
Python defines the search range
The method uses start and end to slice the string, or the full string if they are omitted.
Range
2
Left-to-right scan begins
Python searches for sub starting at the current index, comparing characters case-sensitively.
Search
3
Matches increment the counter
Each non-overlapping match adds 1. The scan resumes immediately after the matched substring.
Count
=
🔢
Integer result
You get the total number of occurrences—or 0 if the substring was never found.
Important
📝 Notes
count() returns 0 when the substring is not found—it does not raise an error.
Passing an empty string as sub raises ValueError: empty separator.
Negative start or end values are allowed and work like normal slice indices.
For complex patterns (wildcards, alternation), use the re module instead of count().
Wrap Up
Conclusion
The count() method is a fast, readable way to measure substring frequency in Python. Whether you are counting words, letters, or checking that a marker appears the right number of times, count() gives you a clear integer answer in one line.
Keep three rules in mind: it is case-sensitive, matches do not overlap, and optional start/end let you search only part of the string.
Use count() when you need the number of occurrences
Use casefold() first for case-insensitive counting
Pass start and end to search within a slice
Use sub in string when you only need True/False
Handle a return value of 0 as “not found”
❌ Don’t
Expect overlapping matches to be counted separately
Pass an empty string as sub
Assume count() is case-insensitive
Use count() for regex-style pattern matching
Confuse count() with find() (frequency vs index)
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about count()
Use these points when analyzing text in Python.
5
Core concepts
🔢01
Returns int
Number of occurrences.
Purpose
📝02
Three Params
sub, start, end.
Syntax
🔒03
Case-Sensitive
A ≠ a.
Rule
📊04
Word Frequency
Count keywords easily.
Use case
⚠05
No Overlap
"aaa".count("aa") → 1.
Edge case
❓ Frequently Asked Questions
count() returns the number of non-overlapping occurrences of a substring within a string. If the substring is not found, it returns 0.
string.count(sub, start, end). sub is the substring to search for. start and end are optional slice boundaries that limit where the search happens.
Yes. count() distinguishes uppercase from lowercase. "Python".count("python") returns 0, while "Python python".count("python") returns 1.
They limit the search to a slice of the string, like s.count(sub, start, end). The search runs from index start up to—but not including—index end.
No. Matches are non-overlapping. For example, "aaa".count("aa") returns 1, not 2, because the second "aa" would overlap the first match.
count() returns how many times a substring appears. find() returns the index of the first occurrence, or -1 if not found. Use count() for frequency; use find() for location.