idiom for RE matching

Miles semanticist at gmail.com
Wed Jul 25 07:54:52 CEST 2007


On 7/24/07, Gordon Airporte <JHoover at fbi.gov> wrote:
> I did already find that it speeds things up to pre-test a line like
>
> if 'bets' or 'calls' or 'raises' in line:
>         run the appropriate re's

Be careful: unless this is just pseudocode, this Python doesn't do
what you think it does; it always runs the regular expressions, so any
speed-up is imaginary.

>>> line = 'eggs'
>>> bool('spam' or 'ham' in line)
True
>>> 'spam' or 'ham' in line  # Equivalent to: 'spam' or ('ham' in line)
'spam'

AFAIK, the (Python 2.5) idiom for what you want is:

>>> any(s in line for s in ('spam', 'ham'))
False
>>> line = 'Spam, spam, spam, spam'
>>> any(s in line for s in ('spam', 'ham'))
True

-Miles



More information about the Python-list mailing list