how python interprets re matches
fredrik at pythonware.com
Thu Dec 15 22:05:49 CET 2005
Mike Rennie wrote:
> I'm still relatively new to the language, so I hope this question isn't too
> naive. It's a general question for anyone who might have some insights on
> Regular Expressions.
> According to Mark Pilgrim, author of "Dive Into Python", "If the regular
> expression matches, the method will return a Match object, which Python
> considers to be true" (Section 16.3, Example 16.8).
> So, I think "great", and write a function that returns a match object using
> So i make some testcases. The test where there is no match, and the return from
> the function is None, passes.
> The test where there is a match, fails on the assertion:
> AssertionError: <_sre.SRE_Match object at 0x00AFB9C0> != True
> But, shouldn't it accept that as True, based on the info. in Dive Into Python?
"consider to be true" doesn't mean "is True", it means that it's interpreted
as a true value by Python, when Python checks for a truth value:
> I suspect I am being naive in my interpretation of things, so if anyone has any
> feedback on how I might get this to work so my function just returns either
> True (if a match) or False (if no match), I welcome it.
but if you want to check if you have a match, just use the match object.
m = re.search(...)
if not m:
explicitly comparing to boolean constants makes your program more fragile
than it should be. from the style guide:
Don't compare boolean values to True or False using ==
Yes: if greeting:
No: if greeting == True:
Worse: if greeting is True:
More information about the Python-list