by shigemk2

当面は技術的なことしか書かない

Python KeyError in format

ソースコードを追っかけても原因がよくわからなかったけどドキュメントを読んだらなんとなくわかった

>>> a = "{} {'alpha': 1234, 'omega': 5678}".format("test")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: "'alpha'"
>>> a = "{} {{'alpha': 1234, 'omega': 5678}}".format("test")
>>> a
"test {'alpha': 1234, 'omega': 5678}"

Format strings contain “replacement fields” surrounded by curly braces {}. Anything that is not contained in braces is considered literal text, which is copied unchanged to the output. If you need to include a brace character in the literal text, it can be escaped by doubling: {{ and }}.

https://docs.python.org/2/library/string.html#format-string-syntax