What is wrong in my list comprehension?
apt.shansen at gmail.com
Mon Feb 2 12:07:57 EST 2009
>> str.find() returns -1 on failure (i.e. if the substring is not in the
>> given string).
>> -1 is considered boolean true by Python.
> That's an odd little quirk... never noticed that before.
> I just use regular expressions myself.
> Wouldn't this be something worth cleaning up? It's a little confusing
> for failure to evaluate to boolean true even if the relationship isn't
But what would you clean it up to?
str.find can return 0 ... which is a *true* result as that means it
finds what you're looking for at position 0... but which evaluates to
boolean False. The fact that it can also return -1 which is the
*false* result which evaluates to boolean True is just another side of
What's the options to clean it up? It can return None when it doesn't
match and you can then test str.find("a") is None... but while that
kinda works it also goes a bit against the point of having boolean
truth/falsehood not representing success/failure of the function. 0
(boolean false) still is a success.
Raising an exception would be a bad idea in many cases, too. You can
use str.index if that's what you want.
So there's not really a great solution to "cleaning it up" . I
remember there was some talk in py-dev of removing str.find entirely
because there was no really c, but I have absolutely no idea if they
ended up doing it or not.
More information about the Python-list