问题
I'm running the following code:
asset = {}
asset['abc'] = 'def'
print type(asset)
print asset['abc']
query = '{"abc": "{abc}"}'.format(abc=asset['abc'])
print query
Which throws a KeyError error:
[user@localhost] : ~/Documents/vision/inputs/perma_sniff $ python ~/test.py
<type 'dict'>
def
Traceback (most recent call last):
File "/home/user/test.py", line 5, in <module>
query = '\{"abc": "{abc}"\}'.format(abc=asset['abc'])
KeyError: '"abc"'
Format is obviously getting confused by the wrapping {. How can I make sure format only tries to replace the (correct) inner {abc}.
ie, expected output is:
{"abc": "def"}
(I'm aware I could use the json module for this task, but I want to avoid that. I would much rather use format.)
回答1:
To insert a literal brace, double it up:
query = '{{"abc": "{abc}"}}'.format(abc=asset['abc'])
(This is documented here, but not highlighted particularly obviously).
回答2:
wrap the outer braces in braces:
query = '{{"abc": "{abc}"}}'.format(abc=asset['abc'])
print query
{"abc": "def"}
回答3:
The topmost curly braces are interpreted as a placeholder key inside your string, thus you get the KeyError. You need to escape them like this:
asset = {}
asset['abc'] = 'def'
query = '{{"abc": "{abc}"}}'.format(**asset)
And then:
>>> print query
{"abc": "def"}
来源:https://stackoverflow.com/questions/31859757/format-keyerror-when-using-curly-brackets-in-strings