find all index positions

vbgunz vbgunz at gmail.com
Thu May 11 21:13:46 CEST 2006


I thought this to be a great exercise so I went the extra length to
turn it into a function for my little but growing library. I hope you
enjoy :)


def indexer(string, target):
    '''indexer(string, target) -> [list of target indexes]

    enter in a string and a target and indexer will either return a
    list of all targeted indexes if at least one target is found or
    indexer will return None if the target is not found in sequence.

    >>> indexer('a long long day is long', 'long')
    [2, 7, 19]

    >>> indexer('a long long day is long', 'day')
    [12]

    >>> indexer('a long long day is long', 'short')
    None
    '''

    res = []

    if string.count(target) >= 1:
        res.append(string.find(target))

        if string.count(target) >= 2:
            for item in xrange(string.count(target) - 1):
                res.append(string.find(target, res[-1] + 1))

        return res


if __name__ == '__main__':
    print indexer('a long long day is long', 'long')    # -> [2, 7, 19]
    print indexer('a long long day is long', 'day')     # -> [12]
    print indexer('a long long day is long', 'short')   # -> None




More information about the Python-list mailing list