如何在python 3.x中使用string.replace()

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

和2.x一样,使用str.replace()

例:

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

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

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

尝试这个:

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

仅供参考,在string中附加一些任意位置固定的字符 (例如,通过添加后缀-ly将形容词改为副词)时,可以将后缀放在行尾以便于阅读。 为此,在replace()使用split() replace()

 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 
 ss = s.replace(s.split()[1], +s.split()[1] + 'gy') # should have no plus after the comma --ie, ss = s.replace(s.split()[1], s.split()[1] + 'gy')