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)


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)

You can use the count() function with other iterable types as well, such as strings or tuples:

# Count occurrences of a character in a string
text = "hello world"
count_of_l = text.count('l')

print("Count of 'l':", count_of_l)

In this example, count_of_l will be equal to 3 because the character ‘l’ appears three times in the string “hello world”.

Note: the count() method only counts exact matches of the specified element in the iterable. If you want to count elements based on a condition or a function, you may need to use other techniques like list comprehensions or the filter() function.

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. Required fields are marked *