str.format()引发KeyError [英] str.format() raises KeyError
本文介绍了str.format()引发KeyError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下代码引发KeyError
异常:
addr_list_formatted = []
addr_list_idx = 0
for addr in addr_list: # addr_list is a list
addr_list_idx = addr_list_idx + 1
addr_list_formatted.append("""
"{0}"
{
"gamedir" "str"
"address" "{1}"
}
""".format(addr_list_idx, addr))
为什么?
我正在使用Python 3.1.
I am using Python 3.1.
推荐答案
问题是您那里的{
和}
字符未指定格式化键.您需要将它们加倍,因此将代码更改为:
The problem is those {
and }
characters you have there that don't specify a key for formatting. You need to double them up, so change your code to:
addr_list_formatted.append("""
"{0}"
{{
"gamedir" "str"
"address" "{1}"
}}
""".format(addr_list_idx, addr))
这篇关于str.format()引发KeyError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文