Python - string replacement

I was doing the Google's Python course: https://developers.google.com/edu/python/strings

Link to the exercises: https://developers.google.com/edu/python/google-python-exercises.zip

Exercise: ./google-python-exercises/basic/strings2.py

On the following exam:

# 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+++
  return

My answer was:

def not_bad(s):
  not_position = s.find('not')
  bad_position = s.find('bad')
  if bad_position > not_position:
    s = s.replace(s[not_position:],'good')
  return s

When I ran the checker I got the following:

not_bad
 OK  got: 'This movie is good' expected: 'This movie is good'
  X  got: 'This dinner is good' expected: 'This dinner is good!'
 OK  got: 'This tea is not hot' expected: 'This tea is not hot'
 OK  got: "It's bad yet not" expected: "It's bad yet not"

I believe that 'This dinner is good' == 'This dinner is good', but I am not sure why I do not get "OK" status, but "X". I believe that I did not the exam correctly, but the output is still correct. I am new to Python so comments on this would be much appreciated!

Upvotes: 0

Views: 155

Answers (2)

I have managed to resolve it:

def not_bad(s):
  not_position = s.find('not')
  bad_position = s.find('bad')
  if bad_position > not_position:
    s = s.replace(s[not_position:bad_position+3],'good')
  return s

not_bad
 OK  got: 'This movie is good' expected: 'This movie is good'
 OK  got: 'This dinner is good!' expected: 'This dinner is good!'
 OK  got: 'This tea is not hot' expected: 'This tea is not hot'
 OK  got: "It's bad yet not" expected: "It's bad yet not"

Upvotes: 1

pzelasko
pzelasko

Reputation: 2322

You missed the exclamation mark ! in the expected answer. One way to correct your solution would be to specify and incorporate the ending index of replaced substring by using the result of finding bad.

Upvotes: 3

Related Questions