python replace function replaces invalidity

str = "hello,china!"
str.replace("hell","well")
print(str)

 

 

After this discovery does not replace successfully replaced when writing code.

the reason:

In Python strings are immutable object.

So strings need to replace the use of the assignment, generate a new object.

No re-quote before, resulting in the variable points to the previous target, but in reality it has changed, but there is no re-quote it.

So if you want to print out the string after the replacement needs to be reassigned as follows:

str = "hello,china!"
str = str.replace("hell","well")
print(str)

 

This success can replace it! !

Guess you like

Origin www.cnblogs.com/qilin20/p/12207901.html