Python String count() method
Python String count() method
The string.count() method returns the number of times a specified value appears in the string.
Syntax
string.count(sub[, start[, end]])
Parameter
sub: This parameter represents a substring to be searched.
start: This parameter signifies the position to start the search. By default the value is 0.
end: This parameter signifies the position to end the search. By default the value is the end of the string.
Return
This method returns the number of occurrences of substring sub in string S[start:end].
Example 1
# Python String program explaining # the count() method # passing the string str = "Heeelo World "; print("String value:",str) # returning the count of alphabet 'e' print ("The count of 'e' in the string is", str.count('e'))
Output
String value: Heeelo World The count of 'e' in the string is 3
Example 2
# Python String program explaining # the count() method # passing the string str = "This is a python string example"; # Search starts from sub index 'i'. sub = "i"; print ("str.count(sub, 4, 40) : ", str.count(sub, 4, 40)) sub = "python"; print ("str.count(sub) : ", str.count(sub))
Output
str.count(sub, 4, 40) : 2 str.count(sub) : 1
Example 3
# Python String program explaining # the count() method # string to check the occurence string = "Hello world Hello" # counting the occurence of substring in between index 0 and 5 print(string.count("Hello", 0, 5)) # counting the occurence of substring in between index 0 and 15 print(string.count("Hello", 0, 15))
Output
1 1