The count() function in python helps to return the number of occurrences of a given substring in the given string. The method allows specifying the starting and ending of the search in the string.
string.count(substring, start=..., end=...) #Where start(index) is starts from 0
The count() function takes three parameters in these two is optional.
Parameter | Description | Required / Optional |
---|---|---|
substring | a string whose count is to be found | Required |
start | starting index within the string where the search starts | Optional |
end | ending index within the string where the search ends | Optional |
The return value should be an integer showing how many times the substring appears in the given string.
Input | Return Value |
---|---|
string | integer(count) |
# define string
string = "I love oranges, orange are my favorite fruit"
substring = "orange"
count = string.count(substring)
# print count
print("The count of orange is:", count)
Output:
The count of orange is: 2
# define string
string = "I love oranges, orange are my favorite fruit"
substring = "orange"
count = string.count(substring,6,15)
# print count
print("The count of orange is:", count)
Output:
The count of orange is:1