Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
209 views
in Technique[技术] by (71.8m points)

python - str.format() raises KeyError

The following code raises a KeyError exception:

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...