The string.replace() is deprecated on python 3.x. What is the new way of doing this?
As in 2.x, use str.replace()
.
Example:
>>> 'Hello world'.replace('world', 'Guido')
'Hello Guido'
Note also, that the dot binds stronger, than string concantenation, i. e. use parenthesis: ('Hello' + ' world').replace('world', 'Guido')
replace()
is a method of <class 'str'>
in python3:
>>> 'hello, world'.replace(',', ':')
'hello: world'
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
Try this:
mystring = "This Is A String"
print(mystring.replace("String","Text"))
FYI, when appending some characters to an arbitrary, position-fixed word inside the string (e.g. changing an adjective to an adverb by adding the suffix -ly), you can put the suffix at the end of the line for readability. To do this, use split()
inside replace()
:
s="The dog is large small"
ss=s.replace(s.split()[3],s.split()[3]+'ly')
ss
'The dog is largely small'
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)'
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')
来源:https://stackoverflow.com/questions/9452108/how-to-use-string-replace-in-python-3-x