Sub topic 4
Counting occurrences
This chapter assumes you know Python function calls, string indexing, and if statements. It also assumes you know that string methods return new values instead of changing the original. Here you will use str.count to tally substrings, restrict the search to part of a string, and handle the cases where the count surprises you.
The basic call
count returns how many times a substring appears in a string. It never changes the string. It returns an integer.
text = "Mississippi"
print(text.count("i")) # 4
print(text.count("ss")) # 2
print(text.count("p")) # 2
print(text.count("z")) # 0When the substring is missing, count returns 0. It does not raise an error, unlike index. That makes it safe to use without a try block.
The search is case-sensitive, so "Banana".count("b") returns 0. The substring can be one character or many.
Counting is not the same as testing
If you only need to know whether a substring appears, use in. It stops at the first match. count always scans the whole string (or the range you give it). Writing if s.count("x") > 0 works, but if "x" in s is clearer and faster on long text.
Use count when the number itself matters, for example a frequency check or a validation rule such as "exactly one @ in an email address".
address = "[email protected]"
print(address.count("@") == 1) # TrueMatches do not overlap
count scans from left to right. After it finds a match, it continues searching after the end of that match. Overlapping matches are therefore not counted.
print("banana".count("an")) # 2
print("aaaa".count("aa")) # 2, not 3In "aaaa", the first match covers positions 0 and 1. The search resumes at position 2 and finds the second match at positions 2 and 3. A match starting at position 1 is never considered.
If you do need overlapping matches, loop with find and restart one position after each hit:
def count_overlapping(text, sub):
if not sub:
raise ValueError("sub must not be empty")
total = 0
pos = text.find(sub)
while pos != -1:
total += 1
pos = text.find(sub, pos + 1)
return total
print(count_overlapping("aaaa", "aa")) # 3Limiting the range
count accepts optional start and end arguments. They work like slice bounds: start is included and end is excluded.
s = "banana"
print(s.count("a")) # 3
print(s.count("a", 2)) # 2 (searches "nana")
print(s.count("a", 0, 4)) # 2 (searches "bana")This avoids building a temporary slice. It is useful for counting within one field of a fixed-layout record.
Counting without regard to case
Because count is case-sensitive, normalize both the text and the target first. Use casefold for caseless comparison, as covered in an earlier chapter on case handling.
review = "Banana bread, BANANA smoothie"
print(review.casefold().count("banana")) # 2Normalize the target too if it comes from user input: review.casefold().count(term.casefold()).
Common errors
- Expecting overlaps.
"aaaa".count("aa")is2. Use thefindloop above, or a regular expression with a lookahead, when you need3. - Counting words with
count."the cat in the hat".count("the")finds"the"inside longer words too, such as"other". For whole words, split first and count the list items withlist.count. - Forgetting case.
"Yes yes".count("yes")is1.
words = "the cat in the other hat".split()
print(words.count("the")) # 2
print("the cat in the other hat".count("the")) # 3The second result is higher because "other" contains "the".
Exercise
What does "aaaa".count("aaa") return, and why?
Show answer
It returns 1. The first match uses positions 0 to 2. The search resumes at position 3, where only one "a" remains, which is too short to match "aaa". Overlapping matches are not counted.
Exercise
Write an expression that counts how many times "py" appears in the string "Py, py, PY" regardless of case.
Show answer
"Py, py, PY".casefold().count("py") returns 3.