【发布时间】:2017-06-15 20:29:39
【问题描述】:
我遇到了类似的问题
In [5]: x = "this string takes two like {one} and {two}"
In [6]: y = x.format(one="one")
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-6-b3c89fbea4d3> in <module>()
----> 1 y = x.format(one="one")
KeyError: 'two'
我有一个复合字符串,其中包含许多保存在配置文件中的键。对于 8 个不同的查询,它们都使用相同的字符串,除了 1 个键是不同的设置。我需要能够替换该文件中的密钥以保存字符串以供以后使用:
"this string takes two like one and {two}"
如何使用format 一次替换一个键?
【问题讨论】:
-
你至少可以做
y = x.format(one="one", two="{two}"),但这可能不是最好的方法...... -
y = x.replace('{one}', 'whatever')怎么样?
标签: python string python-2.7