Looking for python Answers? Try Ask4KnowledgeBase
Looking for python Keywords? Try Ask4Keywords

Python Language Counting number of times a substring appears in a string


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")
>>> s.count("se")
>>> s.count("sea")
>>> s.count("seashells")

By specifying a different value for start, end we can get a more localized search and count, for example, if start is equal to 13 the call to:

>>> s.count("sea", start)

is equivalent to:

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