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


当前回答

简单替换:. 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

其他回答

简单替换:. 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

你可以使用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)'
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')

如2。X,使用str.replace()。

例子:

>>> 'Hello world'.replace('world', 'Guido')
'Hello Guido'

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

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