HOWTO · Python
How to Count Character Occurrences in a Python String
Count a character in a Python string with str.count(), or use Counter, iteration, and regular expressions for other needs.
On this page
Use str.count() to count a character in a Python string. The method is case-sensitive and also accepts a substring; substring matches that overlap are not counted. Use collections.Counter when you need the frequency of every character, a loop when you need custom logic, and a regular expression when you need pattern matching.
Count one character with str.count()
The built-in string method str.count() is the simplest choice for one literal character or substring. It takes the text to search for and returns the number of non-overlapping matches. Letter case matters, so counting "p" and "P" produces separate results.
This self-contained example counts lowercase l in a short string. Replace text and target with your own values; for a multi-character target, the same method counts non-overlapping substring matches.
text = "hello, world!"
target = "l"
count = text.count(target)
print(count)
For example, "aaaa".count("aa") is 2, because the matches are non-overlapping. If you need overlapping substring matches, use a pattern-based approach and define the desired matching behavior explicitly.
Count every character with collections.Counter
collections.Counter in Python’s collections module builds a frequency table from an iterable, including a string. It is useful when you need counts for several characters rather than just one. Retrieve a particular character’s count with bracket access; a character absent from the input has a count of 0.
from collections import Counter
text = "hello, world!"
counts = Counter(text)
print(counts["l"])
print(counts)
The first lookup answers the single-character question, while the Counter object contains the counts for the whole string. You can inspect common entries with counts.most_common(). This approach uses only Python’s standard library, so it does not require NumPy or another third-party package.
Count with a loop or comprehension
An explicit loop makes the comparison and increment steps visible, which is useful when counting needs to include additional conditions or custom processing. Keep the target as a one-character string when the goal is to count individual characters.
text = "hello, world!"
target = "l"
count = 0
for character in text:
if character == target:
count += 1
print(count)
A concise alternative uses sum() with a generator expression. It adds one for each matching character and does not need to build an intermediate list:
text = "hello, world!"
target = "l"
count = sum(character == target for character in text)
print(count)
The loop and generator compare characters exactly as str.count() does for a single-character target, including case sensitivity. For a straightforward count, str.count() is usually easier to read; choose explicit iteration when it makes surrounding logic clearer.
Count a character with a regular expression
Use the standard-library re module when the target is a pattern or when regex matching is already part of the task. A raw character is not always interpreted literally in a regular expression: symbols such as . and * have special meanings. If the target comes from user input and should be matched as literal text, pass it through re.escape() before building the pattern.
import re
text = "hello, world!"
target = "l"
pattern = re.escape(target)
count = len(re.findall(pattern, text))
print(count)
re.findall() returns the matches, and len() counts them. Regex is more flexible than a literal string count, but it adds pattern syntax to understand. For a plain character or substring, str.count() is simpler. When matching a multi-character pattern, confirm whether the pattern’s normal non-overlapping match behavior fits your task.
Choose the right method
- Use
str.count()for one literal character or substring. It is concise, case-sensitive, and counts non-overlapping substring occurrences. - Use
collections.Counterwhen you need a frequency table for all characters or several lookups. - Use a loop or a
sum()generator when each character needs custom handling as it is examined. - Use
rewhen the search is genuinely a pattern; escape user-supplied literal text withre.escape().
For most single-character questions, start with str.count(). The alternatives solve different needs: all-character statistics, explicit per-character logic, or pattern matching. For related string-search techniques, see this Python tutorial.