Sub topic 4
Counting occurrences
This chapter covers str.count, the method that tells you how many times a substring appears in a string. It assumes you can read basic Python, know what str literals and indexing are, and understand if statements, for loops, lists, and tuples. It also assumes you have seen that string methods return new values, which the earlier chapter on immutability covered.
What count does
count takes a substring and returns an int: the number of times that substring appears in the string. It never changes the string, and it never raises an error for a missing substring. It returns 0 instead.
text = "banana"
print(text.count("a")) # 3
print(text.count("an")) # 2
print(text.count("x")) # 0
print(text) # bananaThe full signature is str.count(sub[, start[, end]]). The sub argument must be a str. Passing an integer or a tuple raises TypeError.
try:
"banana".count(("a", "n"))
except TypeError:
print("count accepts one string only")This differs from startswith and endswith, which accept a tuple of alternatives. If you need to count several different substrings, you call count once per substring.
Matches do not overlap
count scans left to right. After it finds a match, it continues searching after the end of that match. Characters already used in one match cannot be part of the next one.
print("aaaa".count("aa")) # 2
print("banana".count("ana")) # 1In "aaaa", the matches are at positions 0 and 2, so the answer is 2. Overlapping matches would also start at position 1, which would give 3. In "banana", "ana" appears at positions 1 and 3, and the two matches share the a at position 3. count finds the first one and skips past it, so it reports 1.
This is the most common surprise with count. If your problem needs overlapping matches, such as counting repeated patterns in DNA sequences, count gives the wrong answer. A short loop with find fixes it:
def count_overlapping(text, sub):
if not sub:
raise ValueError("sub must not be empty")
total = 0
start = 0
while True:
i = text.find(sub, start)
if i == -1:
return total
total += 1
start = i + 1
print(count_overlapping("aaaa", "aa")) # 3
print(count_overlapping("banana", "ana")) # 2The loop advances start by one character after each hit, not by the length of the match. That one change allows overlaps. The find method and its start argument are covered in the chapter on finding positions.
Limiting the search with start and end
The optional start and end arguments work like slice bounds. count(sub, start, end) counts matches inside text[start:end], without building that slice.
s = "a-b-c-d"
print(s.count("-")) # 3
print(s.count("-", 2)) # 2
print(s.count("-", 2, 5)) # 1Here s[2:5] is "b-c", which holds one hyphen. As with slices, end is exclusive, and out-of-range values are clamped instead of raising an error.
A match must lie entirely inside the range. A match that begins inside the range but runs past end is not counted:
print("banana".count("na", 0, 3)) # 0, the range is "ban"
print("banana".count("na", 0, 4)) # 1, the range is "bana"Negative values count from the end of the string, the same as in slicing. For example, s.count("-", -3) searches only the last three characters.
The empty substring
Counting the empty string is legal and returns a surprising number. The empty string "matches" at every gap between characters, including before the first character and after the last.
print("abc".count("")) # 4
print("".count("")) # 1
print("abc".count("", 1)) # 3
print("abc".count("", 4)) # 0For a range of length n, the result is n + 1. If start is past the end of the string, the result is 0. This matters when the substring comes from user input or a variable. An empty value silently produces len(text) + 1, not an error. If an empty substring makes no sense for your code, check for it before calling count.
Case sensitivity
count compares characters exactly. "The" and "the" are different substrings.
text = "The cat and the hat. THE end."
print(text.count("the")) # 1
print(text.lower().count("the")) # 3
print(text.casefold().count("the")) # 3To count regardless of case, convert the text first. Use casefold instead of lower when the text may contain non-English characters, because it handles cases like the German ß. Convert the search term the same way, so both sides use the same form:
def count_ci(text, sub):
return text.casefold().count(sub.casefold())
print(count_ci("Straße STRASSE strasse", "strasse")) # 3Case conversion can change the length of a string. "Straße".casefold() is "strasse", which is one character longer. Because of this, never take an index found in the casefolded copy and use it on the original text. Counting is safe, because it returns only a number.
Counting several things at once
Because count takes one substring, counting a group of characters means calling it for each member and adding the results:
word = "Education"
vowels = sum(word.lower().count(v) for v in "aeiou")
print(vowels) # 5This is fine for a small group. Each call scans the whole string, so the cost is one pass per character you ask about. When you need counts for many different characters, or for all of them, collections.Counter makes one pass and returns every count:
from collections import Counter
counts = Counter("banana")
print(counts) # Counter({'a': 3, 'n': 2, 'b': 1})
print(counts["a"]) # 3
print(counts["z"]) # 0Counter counts single items, so it works for characters but not for multi-character substrings. For a substring, use count.
Counting lines and words
count can count line breaks, but a result of n newlines does not always mean n lines.
text = "one\ntwo\nthree"
print(text.count("\n")) # 2
print(len(text.splitlines())) # 3
text2 = "one\ntwo\nthree\n"
print(text2.count("\n")) # 3
print(len(text2.splitlines())) # 3The first string has two newlines but three lines. The second has a trailing newline, so the count matches the number of lines. splitlines gives the line count in both cases, and it also handles \r\n endings.
Words follow the same pattern. Counting spaces fails when there are repeated or leading spaces:
text = " a b "
print(text.count(" ")) # 5
print(len(text.split())) # 2Use split() with no arguments to count words, because it collapses runs of whitespace.
Common errors
| Mistake | What happens | Fix |
|---|---|---|
| Expecting overlapping matches | `"aaaa".count("aa")` gives 2, not 3 | Loop with `find` and advance by one |
| Forgetting case differences | `"The".count("the")` gives 0 | Convert both sides with `casefold` |
| Passing a tuple | `TypeError` | Call `count` once per substring |
| Empty substring from a variable | Result is `len(text) + 1` | Check for an empty value first |
| Using `count` to test presence | Works, but scans the whole string | Use `in`, which stops at the first match |
| Counting `"\n"` to get lines | Off by one when there is no trailing newline | Use `len(text.splitlines())` |
The presence test deserves a note. Writing if text.count("x") > 0: returns the right answer, but count must scan the entire string to produce a total, while "x" in text stops at the first match. Use in when you only need a yes or no.
Lists have a count too
Lists have a count method with the same name, but it counts elements, not substrings. It takes one argument and has no start or end.
print([1, 2, 2, 3, 2].count(2)) # 3
print("1223 2".count("2")) # 3When you call .count on a variable, check whether it is a str or a list. The semantics differ, particularly for multi-character arguments.
Exercise
What do "aaaa".count("aa") and "abc".count("") return, and why?
Show answer
The first returns 2, because count scans left to right and skips past each match, so the matches at positions 0 and 2 are counted and the overlapping one at position 1 is not. The second returns 4, because the empty string matches at every gap between characters: before "a", between each pair, and after "c", which is len("abc") + 1.
Exercise
Write a function countciwords(text, word) that returns how many times word appears in text, ignoring case, using count. Then explain why countciwords("Ban banana BAN", "ban") returns 3 even though only two of those are whole words.
Show answer
def countciwords(text, word): return text.casefold().count(word.casefold()). The call returns 3 because count matches substrings, not whole words: "ban" occurs in "Ban", in the first three letters of "banana", and in "BAN". To count whole words, split the text into words first, for example sum(1 for w in text.casefold().split() if w == word.casefold()), or use the re module with word boundaries.
Exercise
A DNA string is "ATATATA". How many times does "ATA" appear if overlaps are allowed, and what does "ATATATA".count("ATA") return?
Show answer
With overlaps, "ATA" starts at positions 0, 2, and 4, so the answer is 3. The count method returns 2, because after matching at position 0 it resumes at position 3 and finds the next match at position 4. The overlapping match at position 2 is skipped.