103
Python String Count() Method
It returns the number of occurences of substring in the specified range. It takes three parameters, first is a substring, second a start index and third is last index of the range. Start and end both are optional whereas substring is required.
Signature
Parameters
- sub (required)
- start (optional)
- end (optional)
Return Type
It returns number of occurrences of substring in the range.
Let’s see some examples to understand the count() method.
Python String Count() Method Example 1
Output:
occurences: 2
Python String Count() Method Example 2
Here, we are passing second parameter (start index).
Python String Count() Method Example 3
Output:
occurences: 5
The below example is using all three parameters and returning result from the specified range.
Python String Count() Method Example 4
Output:
occurences: 1
It can count non-alphabet chars also, see the below example.
Python String Count() Method Example 5
Output:
occurences: 3
Next TopicPython Strings