How to use string.replace() in python 3.x

2019-01-02 17:44发布

问题:

The string.replace() is deprecated on python 3.x. What is the new way of doing this?

回答1:

As in 2.x, use str.replace().

Example:

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

Note also, that the dot binds stronger, than string concantenation, i. e. use parenthesis: ('Hello' + ' world').replace('world', 'Guido')



回答2:

replace() is a method of <class 'str'> in python3:

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


回答3:

The replace() method in python 3 is used simply by:

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


回答4:

Try this:

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


回答5:

FYI, when appending some characters to an arbitrary, position-fixed word inside the string (e.g. changing an adjective to an adverb by adding the suffix -ly), you can put the suffix at the end of the line for readability. To do this, use split() inside replace():

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


回答6:

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')


标签: