Count the number of occurrences of a character in a string
In Python's str.count()
, counts a character's appearances in a string:
No surprises here, "a" appears 3 times in "banana".
Counting within a range
str.count()
can be more precise, it counts within a specific portion of the string:
Let’s get comprehensive with collections.Counter
If you need a character census:
With Counter
, we can even run a full-scale tally.
Ignoring case like a gentleman
Want to count regardless of case?
Use .lower()
to treat 'A' and 'a' as the same character.
Regular expressions for flexing (and matching)
And if you love flexibility and pattern matching:
The re.IGNORECASE
flag makes the search a case-blind investigator.
Going beyond the basics
Time is money, let’s get efficient
When processing massive strings, str.count()
is usually faster — it's an efficient direct method optimized for such tasks. Regular expressions are a bit more resource-hungry due to their fancy flexibility.
Unicode? No problemo!
If you have Unicode characters in your string:
Unicode characters are handled seamlessly with str.count()
.
Additional considerations and edge cases
What’s so special about special characters?
Keep in mind, special characters need escaping in re.findall()
:
The backslash \
signals the dollar sign $
to drop its special character status.
What about overlapping occurrences?
str.count()
does not consider overlapping occurrences:
Despite "aa" appearing twice with overlap, there's only one separate occurrence.
Was this article helpful?