Python Reference ยท String Methods
Python str.count() method
Reference for Python str.count(): count non-overlapping occurrences of a substring, use start and end bounds, and avoid the empty-string and overlap surprises.
The str.count() method returns how many times a substring appears in a string. Matches never overlap: after one match, the search continues after its end. The search is case-sensitive.
You can limit the search to a slice of the string with the optional start and end arguments, which work like slice indexes.
print("banana".count("a")) # 3
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
str.count(sub) str.count(sub, start) str.count(sub, start, end)
| Name | Description |
|---|---|
sub |
The substring to count. Must be a str. |
start |
Optional. Index where the search begins (default 0). Negative values count from the end. |
end |
Optional. Index where the search stops, exclusive (default len(s)). |
Return value: a non-negative int.
Raises: TypeError if sub is not a string, for example a tuple or an integer.
Usage notes
- Non-overlapping.
"aaaa".count("aa")is2, not3. Count overlaps with a loop over start positions, or a regular expression with a lookahead such as(?=aa). - Case-sensitive. Lower-case both sides, for example
s.lower().count("the"), for a caseless count. - Empty substring.
s.count("")returnslen(s) + 1, because an empty string matches at every position including both ends. - Substring, not word.
"the"also matches inside"other". To count whole words, split first:words.count("the")on a list does an exact element comparison. - Counting one character in a list uses
list.count(), which compares whole elements.collections.Countercounts everything in one pass. - Slice bounds follow the slicing rules, so out-of-range values are clipped and never raise.
- Cost. Each call scans the string once, so counting many different substrings means many scans.
Related
str.find(),str.index(),str.replace(),str.startswith(),len()- Lessons: Strings, String methods