首页 > 解决方案 > Python:多次使用格式化字符串的键

问题描述

我有一个格式化字符串:

test = 'I am a string and {key}'

现在我想多次使用这个字符串的键来动态改变字符串:

test = test.format(key="hello1")
print(test)
test = test.format(key="hello2")
print(test)

在此之后我得到一个KeyError: "key"因为键“键”被覆盖。如何在不复制字符串copy(test)且不重命名字符串的情况下多次访问密钥?是否有另一种方法来格式化字符串并保留密钥?

标签: pythonpython-3.xstringformatkeyerror

解决方案


编辑:您问题的最终答案是否定的。您不能用不同的数据覆盖变量,然后重新使用该变量,就好像您没有更改任何内容一样。据我所知,没有一种语言会允许这样的语法,因为它不合逻辑。

当你用 声明一个变量时test =,你正在分配test一个内存位置。当您使用 重新声明时test.format,您将分配test到一个完全不同的内存位置。证明:

test = 'I am a string and {key}'
print(id(test))

test = test.format(key="hello1")
print(id(test))

> 1550435806864
> 1550435807104

你能从理论上存储原始内存位置并抓住它吗?也许,如果垃圾收集还没有清理那个位置。你应该吗?绝对不。我猜想这样做会导致内存泄漏。


原始答案

您正在用一个全新的字符串覆盖您的模板字符串。试试这个:

template = 'I am a string and {key}'

test = template.format(key="hello")
print(test)
test = template.format(key="goodbye")
print(test)

推荐阅读