This code may work better for you:
def count_del(string, substring):
occurs = 0
#using the find method to increment counter
#if -1, no substring found, if 0 or >0, substring found
#increment counter and search to the right of substring
while string.find(substring) >= 0:
string = string[string.find(substring) + len(substring):]
#truncate all strings until substring + len(substring)
#search only items in the right of substring
occurs +=1
return occurs
=========
leaving my older code and comments as there is reference in the comments to this section.
Every time you go into the loop, you are decreasing the length of the string. That messes up your value of i in the if statement.
if string[i:i + len(substring)] == substring:
When you go into the loop for the first time, i is 0, therefore, your if statement converts to:
if string[0:0 + 2] == substring:
When you go into the loop for the second time, i is 1, therefore, your if statement converts to:
if string[1:1 + 2] == substring:
I don't think this is what you want to do. You still want to search from 0 instead of 1.
If you change your code as follows, it will give you the desired result
def count_delete(string, substring):
occurrence = 0
while len(string) >= len(substring):
#for i in range(len(string)): replaced for loop with while
#check the string from beginning to len of substring
if string[:len(substring)] == substring:
occurrence += 1
#string = string.replace(substring, "", 1)
#instead of removing the entire substring,
#you may want to check if there are more occurrences of the same
#to do that, use the below line
string = string[1:]
#this will find 2 'abab' in 'abababb' instead of 1
#if thats what you want
return occurrence