How to Count How Many Times Text Appears in a String in Python with count()
How many times does the letter r appear in "strawberry"? Python's count() answers that in one call, for a single letter or for longer text. This guide counts three things in one word on Python 3.15.2.
Syntax
<number> = <text>.count(<sub>, <start>, <end>)
| Part | What it means |
|---|---|
<text> | The string to search |
<sub> | The letter or text to count |
<start>, <end> | Optional. Count only between these positions, the way slicing does. Leave them out to search the whole string |
<number> | How many times <sub> appears, as a whole number |
The Python documentation says str.count() will "Return the number of non-overlapping occurrences of substring sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation."
The Example
The word strawberry. The script counts the letter r, the pair rr, and a capital R.
Prerequisites
- uv and Python 3. This guide uses uv 0.13.10 with Python 3.15.2, in a project made with
uv init.
Step 1: Write the Script
word = "strawberry"
print(word.count("r"))
print(word.count("rr"))
print(word.count("R"))

Step 2: Run It
uv run python letters.py
3
1
0

The letter r appears three times: once in "straw" and twice in "berry". The pair rr appears once, in "berry". A capital R gave 0, because count() treats capital and small letters as different and the word has no capital R. The command works unchanged in PowerShell.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Expecting count() to ignore capital letters | "Strawberry".count("s") gave 0 | Lowercase the text first: "Strawberry".lower().count("s") gave 1 |
| Counting a word in a sentence | Matches inside other words count too: "the cat scattered".count("cat") gave 2 | Split the sentence into words and count in that list: "the cat scattered".split().count("cat") gave 1 |
FAQ
Why does "aaaa".count("aa") give 2?
Because count() counts "non-overlapping occurrences". It finds aa at the start, carries on after that match, and finds the second aa. The aa in the middle overlaps both, so it isn't counted.
Can I start counting later in the string?
Yes, with <start>. word.count("r", 4) gave 2: positions start at 0, so position 4 is the w, and the r in "str" came before it.
Conclusion
word.count("r") returned 3 for "strawberry", word.count("rr") returned 1, and word.count("R") returned 0, because the count is case-sensitive.
Additional Resources
- str.count() — the method and its optional start and end.
- Text sequence type: str — Python strings and their methods.
