0

Im trying to add every substring that occurs in my list, so in the word "hello" it would return [2,3] as the index values found in the string. I don't know how to have it re-iterate after every substring is found.

def myFind(string,substring):

    if (string.find(substring) == -1):
        return []

    i = 0
    list = []
    while i < len(string):
        x = string.find(substring)
        list.append(x)
        i +=1
    return list
print (myFind("Hello","l"))
S. Nick
  • 12,879
  • 8
  • 25
  • 33
Nitro
  • 1
  • 1
    [`str.find()`](https://docs.python.org/3/library/stdtypes.html#str.find) as an extra optional argument `start`... So just pass `i` to find: `string.find(substring, i)` – Tomerikoo Jun 04 '20 at 19:14
  • 1
    Does this answer your question? [How to find all occurrences of a substring?](https://stackoverflow.com/questions/4664850/how-to-find-all-occurrences-of-a-substring) @A-y you are right. Why didn't you flag it? – Tomerikoo Jun 04 '20 at 19:16
  • 1
    Just figured out how to flag :) – A-y Jun 04 '20 at 19:19

2 Answers2

1

You can use the module, re:

import re

s = 'hello'

print([i.start() for i in re.finditer('l', s)])

Output:

[2, 3]
Red
  • 26,798
  • 7
  • 36
  • 58
0

Here's how you could do it with a list comprehension:

def my_find(s,sub):
    "get all indices of substring sub in string s"
    return [i for i in range(0,len(s)-len(sub)+1) if s[i:i+len(sub)] == sub]
bug_spray
  • 1,445
  • 1
  • 9
  • 23