The string.replace() is deprecated on python 3.x. What is the new way of doing this?
replace()
is a method of <class 'str'>
in python3:
>>> 'hello, world'.replace(',', ':')
'hello: world'
Try this:
mystring = "This Is A String"
print(mystring.replace("String","Text"))
ss = s.replace(s.split()[1], +s.split()[1] + 'gy')
# should have no plus after the comma --i.e.,
ss = s.replace(s.split()[1], s.split()[1] + 'gy')
Simple Replace: .replace(old, new, count) .
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
The replace() method in python 3 is used simply by:
a = "This is the island of istanbul"
print (a.replace("is" , "was" , 3))
#3 is the maximum replacement that can be done in the string#
>>> Thwas was the wasland of istanbul
# Last substring 'is' in istanbul is not replaced by was because maximum of 3 has already been reached
You can use str.replace() as a chain of str.replace(). Think you have a string like 'Testing PRI/Sec (#434242332;PP:432:133423846,335)'
and you want to replace all the '#',':',';','/'
sign with '-'
. You can replace it either this way(normal way),
>>> str = 'Testing PRI/Sec (#434242332;PP:432:133423846,335)'
>>> str = str.replace('#', '-')
>>> str = str.replace(':', '-')
>>> str = str.replace(';', '-')
>>> str = str.replace('/', '-')
>>> str
'Testing PRI-Sec (-434242332-PP-432-133423846,335)'
or this way(chain of str.replace())
>>> str = 'Testing PRI/Sec (#434242332;PP:432:133423846,335)'.replace('#', '-').replace(':', '-').replace(';', '-').replace('/', '-')
>>> str
'Testing PRI-Sec (-434242332-PP-432-133423846,335)'