Finding a string multiple times in another String - Python

后端 未结 7 1380
死守一世寂寞
死守一世寂寞 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:38

    def multi_find (s, r):
        s_len = len(s)
        r_len = len(r)
        n = [] # assume r is not yet found in s
    
        if s_len >= r_len:
            m = s_len - r_len
            i = 0
    
            while i < m:
                # search for r in s until not enough characters are left
                if s[i:i + r_len] == r:
                    n.append(i)
                i = i + 1
        print (n)
    
    multi_find("abcdefabc. asdli! ndsf acba saa abe?", "abc")
    

    Pretty much just replace n with a list so you can keep adding values to it as you find them. You also need to be incrementing i even when a match is found, it would have been stuck in a loop forever except that you had the while n == -1 constraint that made it stop as soon as a match was found.

提交回复
热议问题