Explore Python's count() method for strings. Learn how to count occurrences of substrings within strings with examples. Returns the number of times a specified value occurs in a string
Return the number of times the value "apple" appears in the string:
txt = "I love apples, apple are my favorite fruit"
x = txt.count("apple")
print(x)
The count()
method returns the number of times a specified value appears in the string.
string.count(value, start, end)
Parameter | Description |
---|---|
value | Required. A String. The string to value to search for |
start | Optional. An Integer. The position to start the search. Default is 0 |
end | Optional. An Integer. The position to end the search. Default is the end of the string |
Search from position 10 to 24:
txt = "I love apples, apple are my favorite fruit"
x = txt.count("apple", 10, 24)
print(x)
#python