假设我们有这样的代码:
placehold = "6"
string1 = "this is string one and %s" % placehold
print string1
placehold = "7"
print string1
运行时,两个打印语句都返回,好像占位符始终为 6。但是,就在第二个语句运行之前,占位符更改为 7,那么为什么它没有动态反射(reflect)在字符串中?
此外,您能否建议一种使字符串返回 7 的方法?
谢谢
最佳答案
当你这样做时:
string1 = "this is string one and %s" % placehold
您正在创建一个字符串 string1
,其中 %s
替换为 placehold
的值 稍后更改 placehold< 的值
它不会对 string1
产生任何影响,因为字符串不包含变量的动态属性。为了反射(reflect)更改值的字符串,您必须再次重新分配字符串。
或者,您可以使用 .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
关于python - 为什么字符串变量在更改时不更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39818267/