Reputation: 31
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
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