xxxxxxxxxx
# Syntax - str.replace(old, new [, count])
song = 'cold, cold heart'
replaced_song = song.replace('o', 'e')
# The original string is unchanged
print('Original string:', song)
print('Replaced string:', replaced_song)
song = 'let it be, let it be, let it be'
# maximum of 0 substring is replaced
# returns copy of the original string
print(song.replace('let', 'so', 0))
xxxxxxxxxx
# string.replace(old, new, count), no import is necessary
text = "Apples taste Good."
print(text.replace('Apples', 'Bananas')) # use .replace() on a variable
Bananas taste Good. <---- Output
print("Have a Bad Day!".replace("Bad","Good")) # Use .replace() on a string
Have a Good Day! <----- Output
print("Mom is happy!".replace("Mom","Dad").replace("happy","angry")) #Use many times
Dad is angry! <----- Output
xxxxxxxxxx
string = "[Message]"
string = string.replace("[", "")#Removes all [
string = string.replace("]", "")#Removes all ]
print(string)
xxxxxxxxxx
s = 'Some String test'
print(s.replace(' ', '-'))
# Output
# Some-String-test
xxxxxxxxxx
# plz suscribe to my youtube channel -->
# https://www.youtube.com/channel/UC-sfqidn2fKZslHWnm5qe-A
text = "python is too difficult , I have a good experience with it"
#python is too difficult I am using this text for example only
print(text.replace('difficult', 'easy'))
#####output#####
#python is too easy , I have a good experience with it
xxxxxxxxxx
temp_str = 'this is a test'
print(temp_str.replace('is','IS')
print(temp_str)
#################### Result ###########################
thIS IS a test
this is a test
xxxxxxxxxx
text='ramkumar'
text=text.replace("mku","") #'' is empty
print(text)
ans:
ramar
xxxxxxxxxx
phrase = 'old text'
replaced = phrase.replace('old', 'new') # 'new' will replace 'old'
print(replaced) # 'new text'
xxxxxxxxxx
# replace in Python, works like search and replace in word processor
greet = 'Hello Bob'
nstr1 = greet.replace('Bob', 'Jane')
print(nstr1) # Output: Hello Jane
# Initial string doesn't change
print(greet)
# replaces all occurrences of the sub string
nstr2 = greet.replace('o', 'X')
print(nstr2) # Output: HellX BXb
# We can do replace only for number of times
nstr3 = greet.replace('o', 'O', 1)
print(nstr3) # Output: HellO Bob