Counting number of times a substring appears in a string

suggest change

One method is available for counting the number of occurrences of a sub-string in another string, str.count.

str.count(sub[, start[, end]])

str.count returns an int indicating the number of non-overlapping occurrences of the sub-string sub in another string. The optional arguments start and end indicate the beginning and the end in which the search will take place. By default start = 0 and end = len(str) meaning the whole string will be searched:

>>> s = "She sells seashells by the seashore."
>>> s.count("sh")
2
>>> s.count("se")
3
>>> s.count("sea")
2
>>> s.count("seashells")
1

start and end limit the search, and end is exclusive, as in a slice. If start is 13:

>>> s.count("sea", 13)
1

that is equivalent to:

>>> t = s[13:]
>>> t.count("sea")
1

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents