search
str.count
Returns the number of non-overlapping occurrences of substring sub in [start:end]. Overlapping matches are not counted.
str.count(sub[, start[, end]]) Parameters
| Parameter | Purpose |
|---|---|
| sub | substring to count |
| start | optional slice start |
| end | optional slice end |
Examples
>>> 'banana'.count('a')
3 counts every 'a'
>>> 'aaaa'.count('aa')
2 non-overlapping: 'aa' matches at 0 and 2, not 1
>>> 'hello'.count('z')
0 returns 0 when not found (no exception)
>>> 'abc'.count('')
4 empty substring counts as len(str)+1
Gotcha
Overlaps are ignored — 'aaaa'.count('aa') is 2, not 3. For overlapping counts use a regex with a lookahead.
Related methods
str.find
Returns the lowest index in the string where substring sub is found within the slice [start:end]. Returns -1 if the substring is not found, unlike index() which raises ValueError.
str.replace
Returns a new string with all occurrences of substring old replaced by new. If count is given, only the first count occurrences are replaced.
str.index
Like find(), but raises ValueError if the substring is not found. Use when the substring is expected to exist and its absence is an error.
str.rfind
Returns the highest index in the string where substring sub is found within [start:end]. Returns -1 if the substring is not found.
str.startswith
Returns True if the string starts with the given prefix, otherwise False. prefix may also be a tuple of strings to test against multiple candidates.