Python 格式()的kwargs不完整

Python 格式()的kwargs不完整,python,Python,我正在尝试使用不完整的kwargs格式化字符串,如下所示: input is like "{key1} {key2} {key3}" output will be like "value1 value2 {key3}" 我在下面试试 >>> "{key1} {key2} {key3}".format(key1='value1', key2='value2') 但出现以下错误: Traceback (most recent call last): File "<st

我正在尝试使用不完整的kwargs格式化字符串,如下所示:

input is like "{key1} {key2} {key3}"
output will be like "value1 value2 {key3}"
我在下面试试

>>> "{key1} {key2} {key3}".format(key1='value1', key2='value2')
但出现以下错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'key3'
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
KeyError:'key3'
你知道最好的方法是什么吗?

有两种方法可以解决这个问题

  • 双重逃逸模式

    >>> "{key1} {key2} {{key3}}".format(key1='value1', key2='value2')
    
  • 或者将
    {key3}
    作为值传递

    >>> "{key1} {key2} {key3}".format(key1='value1',key2='value2',key3='{key3}')