
count() method –
The count method returns the number of occurrences of a substring in a string.
Syntax –
string.count(substring, start, end)
Substring – the count of the substring that we want.
Start – starting index from where to start the search.
end – the end index of the string where the search ends.
Example –
Let’s say that we have a lyrics and we want to find out how many time any particular word occurs in that lyrics. To do that we can use the count method.
In [1]: lyrics = '''And I know you'll be ok
...: And I know you'll be ok
...: And I know you'll be ok'''
In [2]: lyrics.count('ok')
Out[2]: 3
By default search starts from the beginning of the string till end. If you want, you can change that with the start and end argument.
In [3]: lyrics.count('ok', 25, 100)
Out[3]: 2
You can also count a character.
In [4]: lyrics.count('n')
Out[4]: 6