find all index positions

Gary Herron gherron at islandtraining.com
Thu May 11 13:05:38 EDT 2006


micklee74 at hotmail.com wrote:

>hi
>say i have string like this
>astring = 'abcd efgd 1234 fsdf gfds abcde 1234'
>if i want to find which postion is 1234, how can i achieve this...? i
>want to use index() but it only give me the first occurence. I want to
>know the positions of both "1234"
>thanks
>
>  
>
The regular expression module (called re) has a function (named 
finditer) that gives you what you want here.

The finditer function will find all matches of a pattern in a string and 
return an iterator for them.  You can loop through the iterator and do 
what you want with each occurrence.

 >>> import re
 >>> astring = 'abcd efgd 1234 fsdf gfds abcde 1234'
 >>> pattern = '1234'

Perhaps just find the starting point of each match:

 >>> for match in re.finditer(pattern,astring):
...   print match.start()
...
10
31

Or the span of each match:

 >>> for match in re.finditer(pattern,astring):
...   print match.span()
...
(10, 14)
(31, 35)

Or use list comprehension to build a list of starting positions:

 >>> [match.start() for match in  re.finditer(pattern,astring)]
[10, 31]

And so on ....

Of course, if you wish, the re module can work with vastly more complex 
patterns than just a constant string like  your '1234'.

Gary Herron





More information about the Python-list mailing list