1
2# Python3 program to demonstrate the
3# use of replace() method
4
5string = "geeks for geeks geeks geeks geeks"
6
7# Prints the string by replacing geeks by Geeks
8print(string.replace("geeks", "Geeks"))
9
10# Prints the string by replacing only 3 occurrence of Geeks
11print(string.replace("geeks", "GeeksforGeeks", 3))
1# string.replace(old, new, count), no import is necessary
2text = "Apples taste Good."
3print(text.replace('Apples', 'Bananas')) # use .replace() on a variable
4Bananas taste Good. <---- Output
5
6print("Have a Bad Day!".replace("Bad","Good")) # Use .replace() on a string
7Have a Good Day! <----- Output
8
9print("Mom is happy!".replace("Mom","Dad").replace("happy","angry")) #Use many times
10Dad is angry! <----- Output
1string = "[Message]"
2string = string.replace("[", "")#Removes all [
3string = string.replace("]", "")#Removes all ]
4
5print(string)
1#our text
2text='Hello there how may I help you!'
3 #replacing ("THIS" with "THIS")
4replaced_text=text.replace("!", "?")
5print(replaced_text)
6#output
7"Hello there how may I help you?"
1temp_str = 'this is a test'
2print(temp_str.replace('is','IS')
3print(temp_str)
4
5#################### Result ###########################
6
7thIS IS a test
8this is a test
1text='ramkumar'
2text=text.replace("mku","") #'' is empty
3print(text)
4
5ans:
6ramar
7