I'm trying to see if a string exists in another string with out using Python's predefined functions such as find and index..
Right now what my function takes 2 strings as parameters, one is the string we are going to search while the other string is what we are looking for in the first string.
If the second string exists in the first I want my function to return all the positions it occurs in the first string.
Right now, my function is able to find the first occurrence and return an index, however I want to find multiple occurrences instead of just the first one.
Below is my code:
def multi_find (s, r):
s_len = len(s)
r_len = len(r)
if s_len < r_len:
n = -1
else:
m = s_len - r_len
n = -1 # assume r is not yet found in s
i = 0
while n == -1 and i < m:
# search for r in s until not enough characters are left
if s[i:i + r_len] == r:
n = i
else:
i = i + 1
print (n)
multi_find("abcdefabc. asdli! ndsf acba saa abe?", "abc")
Right now, this will output just "0" because thats where abc occurs first.. How can I get it to return "0" and "6" (The beginning of the second occurrence), basically keep checking after it found one.
I was thinking of something like creating a list of all the places it occurs and then append i to that list but when I tried that, nothing was working for me.