Search substring in a string and get index of all occurances

Fredrik Lundh fredrik at pythonware.com
Wed Jun 21 09:35:17 EDT 2006


K.S.Sreeram wrote:

> effbot's solution finds overlapping occurrences, whereas your solution
> finds non-overlapping occurrences. So efficiency comparisons are not valid.

oops.  my bad.  here's a fixed version:

    result = []; pos = 0
    try:
        while 1:
            pos = mystring.index(substr, pos)
            result.append(pos)
            pos += len(substr)
    except ValueError:
        pass # done

or, if you prefer the generator variant:

    def finditer(string, substr):
        pos = 0
        index = string.index
        try:
            while 1:
                pos = index(substr, pos)
                yield pos
                pos += len(substr)
        except ValueError:
            pass # done

</F> 






More information about the Python-list mailing list