sreekar kaja
sreekar kaja

Reputation: 31

Why does string.count() not give the correct answer if the substring we are searching for overlap?

In the code, count()-ing "CD" gives the correct answer (2) but for count()ing "CDC" it only gives 1. Why?

And how to count "CDC" ?

v="ABCDCDC"
print(v.count("CD"))  #2
print(v.count("CDC")) #1
output
2
1

This works, but is there any simple string method to use?

def count_substring(string, sub_string):
    #return(string.count(sub_string))
    #return
    n=len(string)
    m=len(sub_string)
    sum=0
    for i in range(n-m+1):
        a=i+m
        if string[i:a]==sub_string:
            sum=sum+1
    return(sum)

Upvotes: 1

Views: 96

Answers (1)

iz_
iz_

Reputation: 16593

The documentation here states that count does not count overlapping matches:

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

Return the number of non-overlapping occurrences of substring sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation.

Upvotes: 2

Related Questions