Skip to content

Python count() function

  • by

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)

Output:

Python count() function

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)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.