字符串格式化时如何避免键错误?

时间:2018-08-09 13:39:43

标签: python string-formatting

当我尝试进行字符串格式化时,出现了关键错误

In [9]: template = "%(key_1)s(%(key_2)s, %(key_3)s)"

In [10]: map_var = {"key_2": "some_value"}

In [11]: template % map_var
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-11-b19f23cee642> in <module>()
----> 1 template % map_var

KeyError: 'key_1'


但是,我期望是一个字符串,

"%(key_1)s(some_value, %(key_3)s)"


如何获取此字符串?

0 个答案:

没有答案