find all index positions

Scott David Daniels scott.daniels at
Thu May 11 18:44:35 CEST 2006

micklee74 at wrote:
> astring = 'abcd efgd 1234 fsdf gfds abcde 1234'
> <paraphrase> i want to find all positions of '1234' in astring.</paraphrase>

     def positions(target, source):
         '''Produce all positions of target in source'''
         pos = -1
             while True:
                 pos = source.index(target, pos + 1)
                 yield pos
         except ValueError:

     print list(positions('1234', 'abcd efgd 1234 fsdf gfds abcde 1234'))

     [10, 31]

--Scott David Daniels
scott.daniels at

More information about the Python-list mailing list