Python Count Substrings

The method count() is available to count the number of occurrences of a sub string in a main string.

python count string method

The format of this method is: stringname.count(substring)

This returns an integer number that represents how many times the substring is found in the main string. We can limit our search by specifying beginning and ending positions in the count() method so that the substring position is counted only in that range. Hence, the other form of count() method is:

stringname.count(substring, beg, end)

CopiedCopy Code

str = 'New Delhi' 
n = str.count('Delhi') 
print(n)
str = 'New Delhi' 
n = str.count('e', 0, 6) 
print(n)