Troubleshooting: re.finditer() creates object even when no match found

Steven Bethard steven.bethard at gmail.com
Fri Dec 17 12:50:29 EST 2004


Chris Lasher wrote:
> I know that if I place a finditer() object in an iterative for loop,
> the loop will not execute, but is there some way I can test to see if
> the object contains no matches in the first place?

Basically, you want to peek into an interable.  See my recipes:

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/304373

The short answer is that you can do something like:

try:
     first, iterable = peek(iterable)
except StopIteration:
     # do whatever you do if there are no matches
else:
     # do whatever you do if there are matches

and you won't lose the first element of the iterable.

Steve



More information about the Python-list mailing list