The count method
The count method returns the number of occurrences of a substring in the specified string. In the first parameter of the method, we specify the substring we need, in the second and third optional parameters - the index of the beginning and end of the search, respectively.
Syntax
string.count(substring, [search start index], [search end index])
Example
Let's find the substring 'a', specifying the beginning and end to search for:
txt = 'abcadea'
print(txt.count('a', 0, 2))
Result of code execution:
1
Example
Now let's find the number of all occurrences of the substring 'a' in our string:
txt = 'abcadea'
print(txt.count('a'))
Result of code execution:
3
See also
-
method
find,
which returns the index of the first match of a substring in a string -
method
index,
which finds the index of a matching substring in a string -
method
replace,
which searches and replaces a substring in a string -
method
rfind,
which returns the index of the last match of a substring in a string -
method
rindex,
which returns the highest index of the substring match at the end of the string