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)