[Tutor] Meaning of -1 in Python

Alan Gauld alan.gauld at btinternet.com
Fri Dec 10 18:21:11 CET 2010


"Ben Ganzfried" <ben.ganzfried at gmail.com> wrote

>  n = s.find('not')
>  b = s.find('bad')
>  if n != -1 and b != -1 and b > n:
>    s = s[:n] + 'good' + s[b+3:]
>  return s
>
> It's clear that n!=-1 and b!=-1 means something like : "if in the
> string 's' we find the word "not" and in string 's' we find the word
> "bad."

Exactly the oopsite in fact.
find() returns the index where the string is fouind.
-1 means the string was not found

Thats why inside the if block we can use the n and b values to
slice the string. They represent the positions of the words we
were looking for within the string.

> On a deeper computational level, what is going on here?  What 
> exactly
> does Python take -1 to mean?  Is it saying that since the string 's'
> is indexed starting from 0 to len(s), and since -1 is not part of
> that, that therefore something having the value of -1 will never be 
> in
> the string?

Exactly so. -1 is not a "valid" index (made more confusing by the fact
that in Python it is because Python supports negatiove indexes!
But forget about that temporarily!)

This is a common convention in programming languages and Python
has adopted it. Personally I think a return of None would have made 
more
sense, but history has dictated otherwise!

> If so, then how exactly does using negative numbers to
> count a string work?  I have read something about this earlier...

Python allows you to use negative numbers to  index a string in 
reverse.
So an index of -1 actually indicates the last character, but for 
find() you
have to forget about that...

> Also, does the part: b>n mean, in this case: "bad comes after not in
> the string 's'"?

Yes, if the index of the 'b' in 'bad' is higher than the index of 'n' 
in 'not'
then 'bad' comes after 'not'.

read more about how Python functions work by using the help()
function at the >>> prompt

>>> help(''.find)

Note you only type the name not the () after find

HTH,

Alan G. 




More information about the Tutor mailing list