Return the number of times that the string "code" appears anywhere in the given string, except we'll accept any letter for the 'd', so "cope" and "cooe" count.
count_code('aaacodebbb') → 1
count_code('codexxcode') → 2
count_code('cozexxcope') → 2
My Code
def count_code(str):
count=0
for n in range(len(str)):
if str[n:n+2]=='co' and str[n+3]=='e':
count+=1
return count
I know the right code (just adding len(str)-3
at line 3 will work) but I'm not able to understand why str[n:n+2]
works without '-3' and str[n+3]
Can someone clear my doubt regarding this ?