Skip to main content

count()

The count() function is a String Method in Python that returns the number of occurrences of a specified substring within the string. It takes the substring as an argument and counts how many times it appears in the original string.

Parameter Values

Parameter Description
sub

The substring or sequence of elements to count in the string.

start

Optional. The starting index position to start the search within the string.

end

Optional. The ending index position to end the search within the string.

Return Values

The count() method from String Methods returns an int.

How to Use count() in Python

Example 1:

The count() method returns the number of occurrences of a substring in a string.

sentence = 'Python is easy to learn. Python is versatile.'
print(sentence.count('Python')) # Output: 2
Example 2:

The count() method is case-sensitive.

sentence = 'Python is easy to learn. python is versatile.'
print(sentence.count('python')) # Output: 1
Example 3:

The count() method also works with non-overlapping occurrences.

numbers = '123112311'
print(numbers.count('12')) # Output: 3