Use s.count("char") to count non-overlapping occurrences of a specific character (or substring) in a Python string in a single C-optimized $O(n)$ pass—or use collections.Counter(s) if you need frequency counts for every character in the string at once.
Basic Example
text = "Mississippi"
# 1. Recommended (single character): Use str.count()
count_s = text.count("s")
print(count_s) # Output: 4
# 2. Case-insensitive count: Normalize case first with .casefold() or .lower()
count_m = text.casefold().count("m")
print(count_m) # Output: 1
# 3. Count occurrences within a specific slice [start, end) without copying the string
partial_count = text.count("i", 2, 8) # Searches "ssissi" (indices 2..7)
print(partial_count) # Output: 2
# 4. Count ALL characters at once using collections.Counter
from collections import Counter
freq = Counter(text)
print(freq["p"]) # Output: 2
print(freq) # Output: Counter({'i': 4, 's': 4, 'p': 2, 'M': 1})
Key Details & Edge Cases
str.count()is case-sensitive ("M"$\neq$"m"):"Mississippi".count("m")returns0. Normalize both the string and target character with.casefold()(preferred over.lower()for full Unicode accuracy) when performing case-insensitive counts.- Substring and empty-string edge cases (
"".count("")):s.count(sub)counts non-overlapping occurrences (e.g.,"aaaa".count("aa")returns2, not3). For single characters (len(sub) == 1), overlapping is impossible.- Passing an empty string
s.count("")returnslen(s) + 1(the number of empty gaps between, before, and after characters).
- Counting a set of multiple distinct characters (e.g., all vowels):
s.count()accepts only a single literal character/substring, not a set of characters. Sum.count()calls or use a generator expression:vowels = set("aeiouAEIOU") total_vowels = sum(1 for ch in "Hello World" if ch in vowels) print(total_vowels) # Output: 3 - Why
s.count("x")beatssum(1 for c in s if c == "x")andCounter(s)["x"]for single-character lookups:str.count()runs in a tight C loop (fastsearch) with zero extra memory allocation, whereasCounter(s)hashes every character into a dictionary ($O(n)$ memory) and Python-level generator loops incur per-character bytecode overhead. UseCounter(s)only when querying counts for multiple distinct characters.
Comparison of Character Counting Methods in Python
| Method | Syntax | Time / Space Complexity | Case-Sensitive? | Best Used When |
|---|---|---|---|---|
str.count(char) |
s.count("a") |
$O(n)$ time / $O(1)$ space | Yes | Counting occurrences of a single character (or substring), optionally within [start, end). |
collections.Counter(s) |
Counter(s)["a"] |
$O(n)$ time / $O(k)$ space | Yes | Looking up counts for many different characters in the same string. |
Generator + sum() |
sum(1 for c in s if c in targets) |
$O(n)$ time / $O(1)$ space | Custom | Counting characters matching a condition or set of multiple characters (e.g., vowels/digits). |
len(re.findall(...)) |
len(re.findall(r"[0-9]", s)) |
$O(n)$ time / $O(m)$ space | Configurable (re.I) |
Counting pattern-based character classes when re is already in use. |
You must log in or register to comment.
