There are much better ways but in your code you need to check for when find returns -1
for a non match and increase index by what find returns when you do get a match, you are always appending regardless and only moving one index so if there is a later match you keep finding the same substring start index:
s = 'bobobzbobz'
word = 'bob'
index = 0
instance = []
while index < len(s) - len(word):
f = s.find(word, index)
if f != -1:
instance.append(f)
index = f
index += 1
print (instance)
[0, 2, 6]
You cannot use .count
when you want to consider overlapping substrings as in the example above.
To break it down per iteration using s = 'bobzbobz'
:
s.find(word, 0) -> 0 # s[index:] -> 'bobzbobz'
s.find(word, 1) -> 4 # s[index:] -> 'obzbobz'
s.find(word, 2) -> 4 # s[index:] -> 'bzbobz'
s.find(word, 3) -> 4 # s[index:] -> 'zbobz'
s.find(word, 4) -> 4 # s[index:] -> 'bobz'
s.find(word, 5) -> -1 # s[index:] -> 'obz'
s.find(word, 6) -> -1 # s[index:] -> 'bz'
s.find(word, 7) -> -1 # s[index:] -> 'z'
You get four 4's in your output list as from index 1 to index 4 find is finding the substring word starting at index 4, after that the index has moved past the last bob i.e index 4 so you get -1 added each time as find does not find a match.