Finding a string multiple times in another String - Python

后端 未结 7 1373
死守一世寂寞
死守一世寂寞 2021-01-22 12:00

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

7条回答
  •  伪装坚强ぢ
    2021-01-22 12:51

    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]
    

提交回复
热议问题