iterate lines with regex

Robert Kern robert.kern at gmail.com
Mon Aug 3 20:44:07 CEST 2009


On 2009-08-03 12:29, MRAB wrote:
> Robert Kern wrote:
> [snip]
>>
>> for line in readThis:
>> key_match = key.search(line)
>> if key_match is not None:
>> this_key = key_match.group(1)
>> # ... do something with this_key
>> map_match = map.search(line)
>> if map_match is not None:
>> this_map = map_match.group(1)
>> # ... do something with this_map
>> parcel_match = parcel.search(line)
>> if parcel_match is not None:
>> this_parcel = parcel_match.group(1)
>> # ... do something with this_parcel
>>
> re.search and re.match will return a MatchObject if successful or None
> if unsuccessful. A MatchObject is always true, so you can simplify to:
>
> ...
> if key_match:
> this_key = key_match.group(1)
> # ... do something with this_key
> ...

True, but I prefer to maintain a consistent style for None-testing regardless of 
whether or not I am sure the not-None type will have a suitable __nonzero__ 
implementation.

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco




More information about the Python-list mailing list