Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/339.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/120.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python3中使用.replace()永久更改字符串_Python_Python 3.x - Fatal编程技术网

在Python3中使用.replace()永久更改字符串

在Python3中使用.replace()永久更改字符串,python,python-3.x,Python,Python 3.x,.replace()是否总是需要在print()语句中声明,或者是否可以使用它永久更改字符串?如果是,怎么做?因为字符串是“不可变”对象,所以根本不能对其进行变异。它的所有方法都是如此 .replace还将为您创建一个新的字符串对象 s1 = 'hello' s2 = s1.replace('e', '3') print(s1, id(s1)) print(s2, id(s2)) 您不需要始终在print()中使用.replace() 与下面的示例类似,您可以使用.replace()更改str

.replace()
是否总是需要在
print()
语句中声明,或者是否可以使用它永久更改字符串?如果是,怎么做?

因为字符串是“不可变”对象,所以根本不能对其进行变异。它的所有方法都是如此

.replace
还将为您创建一个新的字符串对象

s1 = 'hello'
s2 = s1.replace('e', '3')
print(s1, id(s1))
print(s2, id(s2))

您不需要始终在
print()中使用
.replace()

与下面的示例类似,您可以使用
.replace()
更改
str
,然后打印更改后的
str

myStr = "I love programming"

myStr = myStr.replace("programming", "chicken Nugget")

print(myStr)

尽量不要对内置str对象进行阴影处理。@12944qwerty谢谢你的建议,只是对它进行了编辑