[Tutor] string indexing

Peter Otten __peter__ at web.de
Sun Jan 19 16:59:39 CET 2014


rahmad akbar wrote:

> hey guys, super  noob here, i am trying to understand the following code
> from google tutorial which i failed to comprehend
> 
> #code start
> # E. not_bad
> # Given a string, find the first appearance of the
> # substring 'not' and 'bad'. If the 'bad' follows
> # the 'not', replace the whole 'not'...'bad' substring
> # with 'good'.
> # Return the resulting string.
> # So 'This dinner is not that bad!' yields:
> # This dinner is good!
> 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
> #code end
> 
>  on the following lines, what is -1, is that index number? 

Python indices start at 0 and the s.find(t) method returns the starting 
index of the first occurence of t in s. That's 0 when s starts with t:

>>> "badmington".find("bad")
0

When t does not occur in s at all the method returns -1, a value that cannot 
be confused with any other possible starting pos.

>  and i dont
> understand the entire second line
> 
> if n != -1 and b != -1 and b > n:

The above line then means (partly in pseudocode):

if ("not" in s) and ("bad" in s) and ("bad" occurs after "not"):

>     s = s[:n] + 'good' + s[b+3:]

s[:n] for a positive integer n means "take the first n characters of s", or 
everything before the occurence of "not". It's basically a shortcut for 
s[0:n]:

>>> s = "This dinner is not that bad!"
>>> s[:3]
'Thi'
>>> n = s.find("not")
>>> s[:n]
'This dinner is '

Likewise s[b:] for a positive integer b means "take all characters after the 
first n of s, or everything including and after the occurence of "bad". 
Again, you can think of it as a shortcut for s[b:len(s)]:

>>> s[3:]
's dinner is not that bad!'
>>> b = s.find("bad")
>>> s[b:]
'bad!'

But we don't want "bad" in the final string, so we have to ad len("bad") or 
3 to b:

>>> s[b+3:]
'!'

So now we have

>>> s[:n]
'This dinner is '

and 

>>> s[b+3:]
'!'

and can put whatever we like in between:

>>> s[:n] + "really delicious" + s[b+3:]
'This dinner is really delicious!'

PS: Note that Python's slicing notation allows steps and negative indices, 
something you might read up on later.



More information about the Tutor mailing list