find all index positions

vbgunz vbgunz at gmail.com
Fri May 12 11:45:43 EDT 2006


Hello John,

Thank you very much for your pointers! I decided to redo it and try to
implement your suggestion. I think I did a fair job and because of your
suggestion have a better iterator. Thank you!

def indexer(string, substring, overlap=1):
    '''indexer(string, substring, [overlap=1]) -> int

    indexer takes a string and searches it to return all substring
    indexes. by default indexer is set to overlap all occurrences.
    to get the index to whole words only, set the overlap argument
    to the length of the substring. The only pitfall to indexer is
    it will return the substring whether it stansalone or not.

    >>> list(indexer('ababababa', 'aba'))
    [0, 2, 4, 6]

    >>> list(indexer('ababababa', 'aba', len('aba')))
    [0, 4]

    >>> list(indexer('ababababa', 'xxx'))
    []

    >>> list(indexer('show chow', 'how'))
    [1, 6]
    '''

    index = string.find(substring)
    if index != -1:
        yield index

    while index != -1:
        index = string.find(substring, index + overlap)
        if index == -1: continue
        yield index

if __name__ == '__main__':
    print list(indexer('ababababa', 'aba'))  # -> [0, 2, 4, 6]
    print list(indexer('ababababa', 'aba', len('aba')))  # -> [0, 4]
    print list(indexer('ababababa', 'xxx'))  # -> []
    print list(indexer('show chow', 'how'))  # -> [1, 6]




More information about the Python-list mailing list