[英]Python: Use key of formatting string multiple times
我有一个格式化字符串:
test = 'I am a string and {key}'
现在我想多次使用这个字符串的键来动态改变字符串:
test = test.format(key="hello1")
print(test)
test = test.format(key="hello2")
print(test)
在此之后我得到一个KeyError: "key"
因为键 "key" 被覆盖了。 如何在不通过copy(test)
复制字符串且不重命名字符串的情况下多次访问密钥? 是否有另一种方法来格式化字符串并保留密钥?
编辑:您问题的最终答案是否定的。 您不能用不同的数据覆盖变量,然后重新使用该变量,就好像您没有更改任何内容一样。 据我所知,没有一种语言会允许这样的语法,因为它不合逻辑。
当您使用test =
声明变量时,您将test
分配给 memory 位置。 当您使用test.format
重新声明时,您将test
分配给完全不同的 memory 位置。 证明:
test = 'I am a string and {key}'
print(id(test))
test = test.format(key="hello1")
print(id(test))
> 1550435806864
> 1550435807104
你能理论上存储原始的 memory 位置并抓住它吗? 也许,如果垃圾收集还没有清理那个位置。 你应该吗? 绝对不。 我猜想这样做会导致 memory 泄漏。
原始答案
您正在用一个全新的字符串覆盖您的模板字符串。 试试这个:
template = 'I am a string and {key}'
test = template.format(key="hello")
print(test)
test = template.format(key="goodbye")
print(test)
除了@SamMorgan 所说的之外,如果您想要多个输出,只需使用 while 或 for 循环,而不是重复输入。 例如,对于定义的次数,使用 for 循环-
test='this is a {key}'
for i in range(5):
c=input()
print(test.format(key=c))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.