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.
Python String count() Method Syntax
It has the following syntax:
count(sub[, start[, end]])
Parameters
- sub (required)
- start (optional)
- end (optional)
Return Type
It returns number of occurrences of substring in the range.
Different Examples for Python String count() Method
Let’s see some examples to understand the count() method.
Python String count() Method Example 1
Let us take an example to demonstrate the working of the string count() method in Python.
# Python count() function example
# Variable declaration
str = "Hello Pythonapp"
str2 = str.count('t')
# Displaying result
print("occurences:", str2)
Output:
occurences: 2
Python String Count() Method Example 2
Let us take an example to demonstrate the working of the string count() method in Python.
# Python count() function example
# Variable declaration
str = "ab bc ca de ed ad da ab bc ca"
oc = str.count('a')
# Displaying result
print("occurences:", oc)
Here, we are passing second parameter (start index).
Python String Count() Method Example 3
Let us take another example to demonstrate the working of the string count() method in Python.
# Python count() function example
# Variable declaration
str = "ab bc ca de ed ad da ab bc ca"
oc = str.count('a', 3)
# Displaying result
print("occurences:", oc)
Output:
occurences: 5
Python String Count() Method Example 4
The given example is using all three parameters and returning result from the specified range.
# Python count() function example
# Variable declaration
str = "ab bc ca de ed ad da ab bc ca"
oc = str.count('a', 3, 8)
# Displaying result
print("occurences:", oc)
Output:
occurences: 1
Python String Count() Method Example 5
It can count non-alphabet chars also, see the given example.
# Python count() function example
# Variable declaration
str = "ab bc ca de ed ad da ab bc ca 12 23 35 62"
oc = str.count('2')
# Displaying result
print("occurences:", oc)
Output:
occurences: 3
Leave a Reply