python - 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)
且不重命名字符串的情况下多次访问密钥?是否有另一种方法来格式化字符串并保留密钥?
解决方案
编辑:您问题的最终答案是否定的。您不能用不同的数据覆盖变量,然后重新使用该变量,就好像您没有更改任何内容一样。据我所知,没有一种语言会允许这样的语法,因为它不合逻辑。
当你用 声明一个变量时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)
推荐阅读
- arrays - 如何在swift中使用规则获取一组数字
- python - Pandas -- 根据条件将 groupby 合并到新的数据框中
- sql - 使用 Visual Studio 在 SQL 数据库中创建表时出错
- docker-compose - 如何自定义生命周期环境名称作为 docker-compose.yaml 的一部分
- javascript - WebView React Native 授权问题
- javascript - 对象之间的 JavaScript 连接
- html - html选择器自定义箭头
- sql - SQL update 语句根据日期更新可能的多行
- postman - 如何在邮递员中获取json数组中的最后一个元素
- java - Apache LDAP API 2:如何处理 ldap 搜索中没有结果