find all index positions

Scott David Daniels scott.daniels at acm.org
Thu May 11 12:44:35 EDT 2006


micklee74 at hotmail.com 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
         try:
             while True:
                 pos = source.index(target, pos + 1)
                 yield pos
         except ValueError:
             pass

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

prints:
     [10, 31]

--Scott David Daniels
scott.daniels at acm.org



More information about the Python-list mailing list