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


当前回答

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

例子:

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

其他回答

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

>>> 'hello, world'.replace(',', ':')
'hello: world'
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')

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

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

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

例子:

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