简体   繁体   English

str.format()引发KeyError

[英]str.format() raises KeyError

The following code raises a KeyError exception: 以下代码引发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))

Why? 为什么?

I am using Python 3.1. 我正在使用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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM