w3resource

Python: Find the first appearance of the substring 'not' and 'poor' from a given string, if 'not' follows the 'poor', replace the whole 'not'...'poor' substring with 'good'. Return the resulting string

Python String: Exercise-7 with Solution

Write a Python program to find the first appearance of the substrings 'not' and 'poor' in a given string. If 'not' follows 'poor', replace the whole 'not'...'poor' substring with 'good'. Return the resulting string.

Sample Solution:

Python Code:

# Define a function named not_poor that takes one argument, 'str1'.
def not_poor(str1):
    # Find the index of the substring 'not' in the input string 'str1' and store it in 'snot'.
    snot = str1.find('not')
    
    # Find the index of the substring 'poor' in the input string 'str1' and store it in 'spoor'.
    spoor = str1.find('poor')

    # Check if 'poor' is found after 'not', and both 'not' and 'poor' are present in the string.
    if spoor > snot and snot > 0 and spoor > 0:
        # Replace the substring from 'snot' to 'spoor+4' (inclusive) with 'good'.
        str1 = str1.replace(str1[snot:(spoor+4)], 'good')
        return str1
    else:
        # If the conditions are not met, return the original 'str1'.
        return str1

# Call the not_poor function with different input strings and print the results.
print(not_poor('The lyrics is not that poor!'))  # Output: 'The lyrics is good!'
print(not_poor('The lyrics is poor!'))          # Output: 'The lyrics is poor!'

Sample Output:

The lyrics is good!
The lyrics is poor!

Flowchart:

Flowchart: Program to find the first appearance of the  substring 'not' and 'poor' from a given string, if  'bad' follows the 'poor', replace the whole 'not'...'poor' substring  with 'good'

Python Code Editor:

Previous: Write a Python program to add 'ing' at the end of a given string (length should be at least 3). If the given string already ends with 'ing' then add 'ly' instead. If the string length of the given string is less than 3, leave it unchanged.
Next: Write a Python function that takes a list of words and return the longest word and the length of the longest one.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/string/python-data-type-string-exercise-7.php