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


当前回答

试试这个:

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

其他回答

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

例子:

>>> 'Hello world'.replace('world', 'Guido')
'Hello Guido'
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')

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

试试这个:

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

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