Another Wart! string.find() [ was: namespace issue? ]
Steven D. Majewski
sdm7g at Virginia.EDU
Thu Jun 21 18:48:31 EDT 2001
On 21 Jun 2001, Michael Powe wrote:
> So now the question is, 'why'? Am I misusing the string.find()
> function? Okay, string.find() returns -1 when the string is not found,
> which would seem to be what I expected, a false result. Maybe python
> doesn't treat -1 as false? Well, I'll try being explicit and testing
> for -1 return. I probably have just confused myself hopelessly.
You got it!
0, 0.0, "", [], (), and None, as well as classes that return 0 from
methods __nonzero__ or __len__ are false.
everything else (unless I missed one ;-) is true.
-1 is true.
But find can't return 0 because it is a valid offset that signifies the
beginning of a string, so it returns -1.
Maybe this should be considered another "Python Wart" : the thing is
that all of the early Python programmers were well used to this sort
of exception in the standard C libraries: zero is an error return
everywhere except where it would be inconvenient, then use negative
numbers as error codes.
It probably *ought* to return None for not found:
"string"[None] yields an exception:
"TypeError: sequence index must be integer"
while "string"[-1] returns "g"
so a coding error is likely to slip thru without an exception.
This is an illogical convention, however it would be very difficult
to root out, because, as you have noted, everyones code is FULL
of explicit checks that string.find does not return -1.
I'ld love to see it fixed, however, I suspect that in this case,
many lines of installed code trumps Computer Programming for Everybody!
-- Steve Majewski
More information about the Python-list
mailing list