On Fri, 01 Jan 2010 21:01:04 -0500, Cousin Stanley <cousinstan...@gmail.com> wrote:

<snip>

    I was not familiar with the re.finditer method
    for searching strings ...

Stanley and Dave --

So far, we've just been using finditer() to perform standard-string searches (e.g. on the word "red"). Since Dave now wants to color multiple words the same color (e.g. the words in redList), we can use a single regular-expression search to locate *all* the words in a list. This eliminates the need to use a "for" loop to handle the list. Here's what I mean:

 >>> import re
 >>> s = "it is neither red nor crimson, but scarlet, you see"

########## individual searches

 >>> [matchobj.span() for matchobj in re.finditer("red", s)]
 [(14, 17)]
 >>> [matchobj.span() for matchobj in re.finditer("crimson", s)]
 [(22, 29)]
 >>> [matchobj.span() for matchobj in re.finditer("scarlet", s)]
 [(35, 42)]

########## one "swell foop"

 >>> redList = "red crimson scarlet".split()
 >>> redList_regexp = "|".join(redList)
 >>> redList_regexp
 'red|crimson|scarlet'
 >>> [matchobj.span() for matchobj in re.finditer(redList_regexp, s)]
 [(14, 17), (22, 29), (35, 42)]

-John
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to