Str.find (sub [, start [, end]]) returns -1 when sub is not found in Python
I did a lot of research on this and came up with the following. As mentioned in several answers here, in traditional programming languages ββor early programming languages, coders handled errors by returning functions back to special values. The consequence of this is that any other code that calls a function that returns a value must check if a value was returned and what is specific to it.
In newer languages ββsuch as Python, we can throw an exception if we cannot produce a result that meets the function specifications. Although exception handling was evident in languages ββway back in the 1960s. The following article explains that it wasn't until the 80s and 90s that design issues were largely resolved. Which language was the first to implement exception handling?
So my conclusion is that before an extended implementation of exception handling that could handle generating errors in many ways, there was a primitive method of returning some arbitrary value in general, and all of this could be done until more complex methods were would be created.
source to share
Returns the smallest index in s where the substring sub is found such that sub is completely contained in
s[start:end]
. Return -1 on error. The default values ββfor start and end and the interpretation of negative values ββare the same as for slices.
Since it must return an index, it makes sense to return -1 when no substring is found (this is usually the behavior in most programming languages ββas well).
If you prefer to Exception
use the string.index
.
source to share
The find method returns the zero index "sub" in the given string. This convention is used in many other languages ββsuch as Java, C #, and JavaScript. If "sub" cannot be found, -1 is returned.
I really can't think of any other reason for this behavior other than common sense and agreement.
source to share
Returning -1 when string search is empty is based on the fact that returning 0 is an ambiguous return value in the case of 0-indexed strings ... consider the following example:
# returns 0 (i.e. found at position 0)
"positional".find("pos")
# return -1 (i.e. for not found at all)
"positional".find("not there")
The same return values ββare used in many programming languages.
source to share