为什么字符串变量更改时不更新

Joh*_*Hon 3 python string string-formatting python-2.7

假设我们有一些像这样的代码:

placehold = "6"
string1 = "this is string one and %s" % placehold

print string1

placehold = "7"
print string1
Run Code Online (Sandbox Code Playgroud)

运行时,两个 print 语句都返回,就好像 placehold 始终为 6。但是,就在第二条语句运行之前,placehold 更改为 7,那么为什么它没有动态反映在字符串中呢?

另外,您能建议一种使字符串返回 7 的方法吗?

谢谢

Moi*_*dri 7

当你这样做时:

string1 = "this is string one and %s" % placehold
Run Code Online (Sandbox Code Playgroud)

您正在创建一个字符串string1,并%s替换为 On 的值,placehold稍后更改它的值placehold不会产生任何影响string1,因为字符串不保存变量的动态属性。为了反映更改值的字符串,您必须再次重新分配该字符串。

或者,您可以使用.format()

string1 = "this is string one and {}"
placeholder = 6
print string1.format(placeholder)
# prints: this is string one and 6

placeholder = 7
print string1.format(placeholder)
# prints: this is string one and 7
Run Code Online (Sandbox Code Playgroud)