Str.find (sub [, start [, end]]) returns -1 when sub is not found in Python

I understand that the method:

str.find

      

will return -1 if sub is not found.

Is there a specific reason for using -1? Is it arbitrary or is it useful to have -1 for some further computation using strings?

I am trying to understand the reasoning, if any, for choosing this value.

+3


source to share


5 answers


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.

0


source


string.find

:

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

.

+3


source


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.

0


source


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.

0


source


-1

is used instead False

because the method is meant to return an integer if found.

0


source







All Articles