Python count() function is used to count the frequency of the character or a substring in a string. This method returns the total count of a given element in a string.
string.count(substring/character, start=, end=)
You can specify the start and end index where you want the search to begin.
Python count() function
Simple example code.
s = 'Hello There' res = s.count('e') print('occurrence of e in string: ', res)
Using Count Method with a Substring.
s = 'abcdabcdabcdbcdefghqwert' res = s.count('abcd') print("Occurrence of 'abcd': ", res)
Output: Occurrence of ‘abcd’: 3
Using both Optional Parameters
s = 'Computer Science' res = s.count('e', 3, 14) print('Occurrence of e from 3rd to 14th index: ', res)
Do comment if you have any doubts or suggestions on this Python essential function topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.