Inconsistent behaviour os str.find/str.index when providing optional parameters

MRAB python at mrabarnett.plus.com
Wed Nov 21 08:32:43 EST 2012


On 2012-11-21 12:43, Giacomo Alzetta wrote:
> I just came across this:
>
>>>> 'spam'.find('', 5)
> -1
>
>
> Now, reading find's documentation:
>
>>>> print(str.find.__doc__)
> S.find(sub [,start [,end]]) -> int
>
> Return the lowest index in S where substring sub is found,
> such that sub is contained within S[start:end].  Optional
> arguments start and end are interpreted as in slice notation.
>
> Return -1 on failure.
>
> Now, the empty string is a substring of every string so how can find fail?
> find, from the doc, should be generally be equivalent to S[start:end].find(substring) + start, except if the substring is not found but since the empty string is a substring of the empty string it should never fail.
>
[snip]
I think that returning -1 is correct (as far as returning -1 instead of
raising an exception like .index could be considered correct!) because
otherwise it whould be returning a non-existent index. For the string
"spam", the range is 0..4.




More information about the Python-list mailing list