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

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!


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")

Got any Python Language Question?