Malik
Malik

Reputation: 195

google python class strings2.py exercise E

What happens at this line ? Why -1 ?

if n != -1 

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):
    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

Upvotes: 0

Views: 355

Answers (2)

jrs
jrs

Reputation: 616

-1 means the substring could not be found.

From the official python documentation:

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.

Upvotes: 2

Kit
Kit

Reputation: 21

str.find(sub[, start[, end]]) Return the lowest index in the string where substring sub is found, such that sub is contained in the slice s[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 if sub is not found.

Upvotes: 0

Related Questions