[Tutor] Meaning of -1 in Python
Ben Ganzfried
ben.ganzfried at gmail.com
Fri Dec 10 15:48:53 CET 2010
I'm currently working through the Google Python tutorial exercises and
had questions about the following function:
def not_bad(s):
# +++your code here+++
# LAB(begin solution)
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."
I'm wondering the following:
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? If so, then how exactly does using negative numbers to
count a string work? I have read something about this earlier...
Also, does the part: b>n mean, in this case: "bad comes after not in
the string 's'"?
Thank you very much.
Sincerely,
Ben
More information about the Tutor
mailing list