count() counts the number of times a substring occurs in a string. The returned value is an integer. By default the whole string is assessed when counting. As an option you can supply a start and end index to search a part of the string only.
Syntax
count(substring, {start, {end}})
– substring is a string you are counting occurrences of in your original string
– start is an optional integer value representing an index position of the original string
– end is an optional integer value representing an index position of the original string
you cannot supply an end value without first supplying a start value
# example # open your favourite Python editor and use the interactive window >>> my_sentence = "One day I was playing out in my garden, you asked to come and play too." >>> my_sentence.count("a") 7
7 instances of “a” were found in my_sentence.
Set a start index and search to the end of the string
>>> my_sentence.count("play", 19) 1
1 instance of the word “play” was found from index 19 (20th character) on to the end of the string. So it searched the string ‘ng out in my garden, you asked to come and play too.’ for the substring “play”.
Using start and end index
>>> my_sentence.count("in", 9, 60) 2
2 instances of “in” were found from index 9 (10th character) to one before index 60, so the 58th character. Research Python indexing and slicing if this confuses you. We searched for “in” in ‘ was playing out in my garden, you asked to come an’
If using start and end optional parameters make sure that the start integer is smaller than the end integer. count() will return a value of 0 (zero) if the end integer is greater than or equal to the start value.
>>> my_sentence.count("play", 71, 5) 0
You can use negative slicing
>>> my_sentence.count("play", -71, -1) 2
Assign the count value to a variable
>>> play_count = my_sentence.count("play") >>> print play_count 2
Previous: center()
Next: endswidth()
Notes:
– counts the number of times a substring is found within a string
– the count is returned as an integer
– by default the whole string is searched
– you can set a start value to search from that index to the end of the string
– if you set a start value you can optionally set an end value to search a substring of the original string
– the end value should not be greater than or equal to the start value, a value of 0 will always be returned
– negative indexing can be used