Question on str.find()


While studying the find function on a string, I find something that is conflicting. If I give a string which is a substring, the find function returns the index of the starting element. If the substring is not found, then it returns -1 to indicate that the substring is not found

Now -1 is also an index of a string which returns the last element of the string. Is this not mutually conflicting ?


Or maybe it is not conflicting at all.
As you are already stating that the function returns -1
to represent the string is not found .
It does not say that it is starting from the index -1.
I hope that made it clear.

String indices always start from 0. -1 is not an index of the string, it is merely a syntactic convenience to point to the element of index len(string)-1.

1 Like

Thanks for the clarification

1 Like

Please look into find function defination:
string. find ( s , sub [, start [, end ]])

Return the lowest index in s where the substring sub is found such that sub is wholly contained in s[start:end] . Return -1 on failure. Defaults for start and end and interpretation of negative values is the same as for slices.

so what does it mean, this is my test string:
mystr="How are you"

it is also list of character, so know print it:

for ch in mystr:
	print(ch,' -> ',i)

you are getting following output
H -> 0
o -> 1
w -> 2
-> 3
a -> 4
r -> 5
e -> 6
-> 7
y -> 8
o -> 9
u -> 10

this are the index for different character .

now try to find how:


you get 0


you get 4


you get 8

this are the lowest index.

as you see, after zero what you get -1, so when it return -1 that mean there is nothing.

if you try this code:


it return
and if try this code:


it still return
So for find function it always count from index zero to last index, but you can give string in any way by referring positive index or negative index. Negetive index just facilitate us by providing negative index.


By observing all this thing i came to one conclusion that nagetive index just facilitate us by providing negative index for string. But python built in function uses only positive index for there internal working and it is good practice for us to relay mainly on positve index.

There is no need to confuse between what find function return and how python facilitate us to refer list by negative index.

1 Like