[Tutor] string indexing
spir
denis.spir at gmail.com
Sun Jan 19 16:41:49 CET 2014
On 01/19/2014 02:59 PM, 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? and i dont
> understand the entire second line
-1 is what find returns if the searched substring is not at all present in the
bigger string: a trick meaning "could not find it". (-1 also means last index,
but is not necessary for find, it would return the positive last index)
> if n != -1 and b != -1 and b > n:
a conditions for which 3 sub-conditions must be met at once
> s = s[:n] + 'good' + s[b+3:]
Watch this:
string: This dinner is not that bad!
indexes: 0 n b -1
s[:n] = s[0:n] = "This dinner is "
s[b+3:] = s[b+3:-1] = "!"
+ concatenates (glues together) bits of strings
denis
More information about the Tutor
mailing list