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
Another alternative using regex
:
>>> import re
>>> haystack = "abcdefabc. asdli! ndsf acba saa abe?"
>>> needle = "abc"
>>> [m.start() for m in re.finditer(r'{}'.format(re.escape(needle)), haystack)]
[0, 6]
The above solution will not work for overlapping sub-strings, like there are 3 'aa'
in 'aaaa'
. So, if you want to find overlapping matches as well, then:
>>> haystack = "bobob"
>>> needle = "bob"
>>> [m.start() for m in re.finditer(r'(?={})'.format(re.escape(needle)), haystack)]
[0, 2]