Bug in string.find; was: Re: Proposed PEP: New style indexing, was Re: Bug in slice type

Bryan Olson fakeaddress at nowhere.org
Fri Aug 26 05:37:31 EDT 2005


Antoon Pardon wrote:
 > Bryan Olson schreef:
 >
 >>Steve Holden asked:
 >>>And what are you proposing that
 >>>find() should return if the substring isn't found at all? please don't
 >>>suggest it should raise an exception, as index() exists to provide that
 >>>functionality.
 >>
 >>There are a number of good options. A legal index is not one of
 >>them.
 >
 > IMO, with find a number of "features" of python come together.
 > that create an awkward situation.
 >
 > 1) 0 is a false value, but indexes start at 0 so you can't
 >    return 0 to indicate nothing was found.
 >
 > 2) -1 is returned, which is both a true value and a legal
 >    index.
 >
 > It probably is too late now, but I always felt, find should
 > have returned None when the substring isn't found.

None is certainly a reasonable candidate. The one-past-the-end
value, len(sequence), would be fine, and follows the preferred
idiom of C/C++. I don't see any elegant way to arrange for
successful finds always to return a true value and unsuccessful
calls to return a false value.

The really broken part is that unsuccessful searches return a
legal index.

My suggestion doesn't change what find() returns, and doesn't
break code. Negative one is a reasonable choice to represent an
unsuccessful search -- provided it is not a legal index. Instead
of changing what find() returns, we should heal the
special-case-when-index-is-negative-in-a-certain-range wart.


-- 
--Bryan



More information about the Python-list mailing list