Python String count() Method

The count() method searches (case-sensitive) the specified substring in the given string and returns an integer indicating occurrences of the substring. By default, the counting begins from 0 index till the end of the string.

Syntax:

str.count(substring, start, end)

Parameters:

  1. substring: A string whose count has to be found.
  2. start: (Optional) The starting index of the string from where the search has to begin . Default is 0.
  3. end: (Optional) The ending index of the string where the search has to end. Default is the end of the string.

Return Value:

An integer value indicating the number of times a substring presents in a given string.

The following example counts the number of occurrences of the given substring:

Example: Counting Case-sensitive Substring
mystr = 'TutorialsTeacher is a free online Tutorials website'

total = mystr.count('Tutorials')
print('Number of occurrences of "Tutorials":', total)

total = mystr.count('tutorials')
print('Number of occurrences of "tutorials":', total)
Output
Number of occurrences of "Tutorials": 2
Number of occurrences of "tutorials": 0

Above, the count() method performs the case-sensitive search in the given string. So, it returns 2 for the substring 'Tutorials' and returns 0 for 'tutorials'.

The following example counts the number of occurrences of a given substring from the given start and end indexes.

Example: Count Substring within Specified Range
mystr = 'TutorialsTeacher is a free online Tutorials website'
substr = 'Tutorials'

total = mystr.count(substr, 0, 15) # start 0, end 15
print('Number of occurrences between 0 to 15 index:',total)

total = mystr.count(substr, 15, 25) # start 15, end 25
print('Number of occurrences between 15 to 25 index:',total)

total = mystr.count(substr, 25) # start 25
print('Number of occurrences from 25th index till end:',total)
Output
Number of occurrences between 0 to 15 index: 1
Number of occurrences between 15 to 25 index: 0
Number of occurrences from 25th index till end: 1

In the above example, the second parameter in the count() method is for starting index, and the third parameter is for ending index within which a substring should be searched. mystr.count(substr, 0, 15) starts searching from the 0 index till 15th index. mystr.count(substr, 25) starts searching from 25 index till the end of the string.

Even you can count a single character in a given string.

Example: Count a Char
mystr = 'Hello World!'
substr = 'l'
total = mystr.count(substr)
print('Number of occurrences:', total)
Output
Number of occurrences: 3

If the specified substring cannot be found, then it returns 0.

Example:
mystr = 'TutorialsTeacher is a free online tutorials website'
substr = 'paid'
total = string.count(substr)
print('Number of occurrences:',total)
Output
Number of occurrences: 0