string.replace()在python 3.x上已弃用。新的方法是什么?


当前回答

你可以使用str.replace()作为str.replace()的一个链。假设你有一个像'Testing PRI/Sec (#434242332;PP:432:133423846,335)'这样的字符串,你想用'-'替换所有的'#',':',';','/'符号。你可以这样替换它(正常方式),

>>> string = 'Testing PRI/Sec (#434242332;PP:432:133423846,335)'
>>> string = string.replace('#', '-')
>>> string = string.replace(':', '-')
>>> string = string.replace(';', '-')
>>> string = string.replace('/', '-')
>>> string
'Testing PRI-Sec (-434242332-PP-432-133423846,335)'

或者这样(str.replace()的链)

>>> string = 'Testing PRI/Sec (#434242332;PP:432:133423846,335)'.replace('#', '-').replace(':', '-').replace(';', '-').replace('/', '-')
>>> string
'Testing PRI-Sec (-434242332-PP-432-133423846,335)'

其他回答

你可以使用str.replace()作为str.replace()的一个链。假设你有一个像'Testing PRI/Sec (#434242332;PP:432:133423846,335)'这样的字符串,你想用'-'替换所有的'#',':',';','/'符号。你可以这样替换它(正常方式),

>>> string = 'Testing PRI/Sec (#434242332;PP:432:133423846,335)'
>>> string = string.replace('#', '-')
>>> string = string.replace(':', '-')
>>> string = string.replace(';', '-')
>>> string = string.replace('/', '-')
>>> string
'Testing PRI-Sec (-434242332-PP-432-133423846,335)'

或者这样(str.replace()的链)

>>> string = 'Testing PRI/Sec (#434242332;PP:432:133423846,335)'.replace('#', '-').replace(':', '-').replace(';', '-').replace('/', '-')
>>> string
'Testing PRI-Sec (-434242332-PP-432-133423846,335)'

试试这个:

mystring = "This Is A String"
print(mystring.replace("String","Text"))

供您参考,当将某些字符附加到字符串中任意位置固定的单词后(例如,通过添加后缀-ly将形容词更改为副词),您可以将后缀放在行尾以提高可读性。要做到这一点,在replace()中使用split():

s="The dog is large small"
ss=s.replace(s.split()[3],s.split()[3]+'ly')
ss
'The dog is largely small'

python 3中的replace()方法被简单地用于:

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

Replace()是python3中<class 'str'>的一个方法:

>>> 'hello, world'.replace(',', ':')
'hello: world'