Format: KeyError when using curly brackets in strings

泄露秘密 提交于 2020-01-21 04:13:16

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!