格式:在字符串中使用大括号时的KeyError [英] Format: KeyError when using curly brackets in strings

查看:625
本文介绍了格式:在字符串中使用大括号时的KeyError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆