格式:在字符串中使用大括号时的KeyError [英] Format: KeyError when using curly brackets in strings
问题描述
asset = {}
asset ['abc'] = 'def'
print type(asset)
print asset ['abc']
query ='{abc:{abc}}'。 abc'])
打印查询
抛出 格式显然被包装 输出是: KeyError
错误:
$ p $ [user @ localhost]:〜/ Documents / vision / inputs / perma_sniff $ python〜 /test.py
< type'dict'>
def
Traceback(最近一次调用的最后一个):
在< module>文件中的第5行/home/user/test.py
query ='\ {abc:{abc}\}'。 {
弄糊涂了。我怎样才能确保格式只尝试取代(正确的)内部 {abc}
。
{abc:def}
$ (我知道我可以使用
json
模块来完成这个任务,但我想避免这个问题。 )
query ='{{abc:{abc}}}'。
(这是 here ,但是没有特别明显地突出显示)。
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.)
To insert a literal brace, double it up:
query = '{{"abc": "{abc}"}}'.format(abc=asset['abc'])
(This is documented here, but not highlighted particularly obviously).
这篇关于格式:在字符串中使用大括号时的KeyError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!