231k views
3 votes
Create a function called notBad that takes a single argument, a string.

It should find the first appearance of the substring 'not' and 'bad'.
If the 'bad' follows the 'not', then it should replace the whole 'not'...'bad' substring with 'good' and return the result.
If it doesn't find 'not' and 'bad' in the right sequence (or at all), just return the original sentence.
For example:
notBad('This dinner is not that bad!'): 'This dinner is good!'
notBad('This movie is not so bad!'): 'This movie is good!'
notBad('This dinner is bad!'): 'This dinner is bad!'

User JimEvans
by
5.7k points

1 Answer

4 votes

Answer:

The Following are the method definition to this question:

def notBad(s):#defining a method notBad that take s variable as parameter

if 'not' not in s or 'bad' not in s: # defining If block that checks "not or bad" is not in the string

return s#return string value

n= s.index('not')#defining n variable that store index value of not

b= s.index('bad')#defining b variable that store index value of bad

if n<b:#defining if block that compare n and b value

return s[:n]+'good'+s[b+3:]#use slicling for remove value and add another value

print(notBad('This dinner is not that bad!'))#call method and print value

print(notBad('This movie is not that bad!'))#call method and print value

print(notBad('This dinner bad!'))#call method and print value

Output:

This dinner is good!

This movie is good!

This dinner bad!

Explanation:

In the above given, method definition a method "notBad" is defined that takes variable "s" as a parameter, which is used for input the string value.

In the next step, an if block, is defined, that checks in string value "not or bad" are not available in the input string. if the condition is true, it will return, that string value.

In the next line "n and b" variable has defined, that store "not and bad" index value, and use if block that the come to its value and use slicing to re remove its value.

User Muhammad Waqar
by
5.7k points