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

标签 python string python-2.7 string-formatting

假设我们有这样的代码:

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/

相关文章:

string - Golang 在字符串 slice 中追加字符串

python - 有没有一种方法可以在 python 的 argparse 中创建参数,如果没有给出值则返回 true

python - 战舰游戏 - if/else 问题

python - Sklearn 如何使用 Joblib 或 Pickle 保存从管道和 GridSearchCV 创建的模型?

python - 是否需要移动才能在 Python 中弹出列表的前面?

python - 如何从 for 循环返回多个具有唯一名称的 pandas 数据帧?

mysql - 使用 mysql 中的新用户定义函数复制 CHARINDEX

python - 找到几个单词,如果删除一个字母将打印出这两个单词

c - 将 ascii 值添加到数组字符时出现总线错误。为什么? (C)

python - 在 Emacs 24.3 和 python-mode.el 中使用 python2.7