program given 👇 w
D
Dhairya Shah Write a program to assign the given sentence to a string variable. Replace the word Blue with Red at all its occurrences.
Given sentence: Blue bottle is in Blue bag lying on Blue carpet
Bright Tutorials
ICSE & CBSE coaching · Nashik Road
Use a string variable to store the sentence and the replace() method to change every occurrence of “Blue” to “Red”.
# store the original sentence
sentence = "Blue bottle is in Blue bag lying on Blue carpet"
# replace all occurrences of 'Blue' with 'Red'
new_sentence = sentence.replace("Blue", "Red")
print(new_sentence)
The output will be:
Red bottle is in Red bag lying on Red carpet
Tip: replace() is case‑sensitive; if you need to replace both “Blue” and “blue”, use re.sub() with the re.IGNORECASE flag.
Know another way to solve it? Share your answer below.
Sign in to post your answer.
Sign in