It provides the count of instances of a substring within the defined range. The function accepts three arguments: the first is the substring, the second is the starting index, and the third is the ending index of the range. While the substring is mandatory, both the start and end indices are optional.
Python String count Method Syntax
It has the following syntax:
count(sub[, start[, end]])
Parameters
- sub (required)
- start (optional)
- end (optional)
Return Type
It provides the count of how many times a substring appears within the specified range.
Different Examples for Python String count Method
Let’s explore a few examples to grasp the functionality of the count method.
Python String count Method Example 1
To illustrate the functionality of the string count method in Python, let us consider an example.
# Python count() function example
# Variable declaration
str = "Hello World"
str2 = str.count('t')
# Displaying result
print("occurences:", str2)
Output:
occurences: 2
Python String Count Method Example 2
To illustrate the functionality of the string count method in Python, let's consider an example.
# 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)
In this instance, we are providing the second argument, which is the starting index.
Python String Count Method Example 3
Let us consider an additional example to illustrate how the string count method functions 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 provided illustration utilizes all three parameters and yields a result based on the designated 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 is capable of counting non-alphabetic characters as well, as illustrated in the example provided.
# 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