shouldn't 'string'.find('ugh') return 0, not -1 ?
J. Clifford Dyer
jcd at sdf.lonestar.org
Wed Oct 31 16:09:52 CET 2007
On Wed, Oct 31, 2007 at 03:55:49PM +0100, jelle feringa wrote regarding Re: shouldn't 'string'.find('ugh') return 0, not -1 ?:
> There is a subtle point though.
> If the substring is not found '_'.find(' '), will return -1
> Semanticly, I was expecting the that if the substring was not found,
> the conditional statement would not be found.
> However, python evaluates -1 to True, so that is what I do find
> So, I was arguing that '_'.find(' ') might return 0, however that is
> obviously ambigious, since 0 might be an index as well.
> So, perhaps I should rephrase and ask, why if -1 evaluates to True?
> I think that's pretty ugly...
It is ugly, but there's no alternative. In essence, you can't do a truth-test on it, because you're not testing the truth of the find statement. The statement that you want to test the truth of is s.find(q) >= 0. In other words, you want to see that the substring was found at a valid (non-negative) location. As someone else pointed out, it would make more sense to use None instead of -1. You still couldn't use `if s.find(q):` because you'd get a false result for a substring found at the beginning of the string, but the return value would make more intuitive sense.
Witness also the problem of actually using the result of find:
will yield a valid part of the string (the last character) when q is not found. If it evaluated to none, you'd get a respectable TypeError instead.
But you still wouldn't--and never will--be able to say `if s.find(q)`, because valid array indices can be either true or false.
More information about the Python-list