Python 3 reference · String Methods
Python String count() Method
Return the number of non-overlapping occurrences of a substring, optionally only between start and end positions.
Python 3 Since 3.0
Syntax
str.count(sub, start=0, end=len(s))
Parameters
| Parameter | Description |
|---|---|
sub |
The substring to count. |
start, end optional |
Only search this slice. |
Return value
An int.
Examples
text = "banana"
print(text.count("a"), text.count("an"), text.count("x"))
Output
3 2 0
print("aaaa".count("aa")) # non-overlapping: 2, not 3
Output
2
sentence = "the cat and the hat"
print(sentence.count("the"), sentence.count("the", 5))
Output
2 1
For counting every word or character at once, use collections.Counter.
Version history
| Version | Change |
|---|---|
| Python 3.0 | Added |
Related
str.find()· Return the lowest index where a substring is found, or -1 if it isn't. Optional start and end limit the search.str.index()· Return the lowest index of a substring, like find(), but raise ValueError when it is not found.str.split()· Split the string into a list of substrings at a separator. With no separator it splits on any whitespace.- Python Strings · tutorial