C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Python String Count() MethodIt 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
count(sub[, start[, end]]) Parameters
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
# Python count() function example
# Variable declaration
str = "Hello TheDeveloperBlog"
str2 = str.count('t')
# Displaying result
print("occurences:", str2)
Output: occurences: 2 Python String Count() Method Example 2
# 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
# 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 The below example is using all three parameters and returning result from the specified range. Python String Count() Method Example 4
# 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 It can count non-alphabet chars also, see the below example. Python String Count() Method Example 5
# 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
Next TopicPython Strings
|