【发布时间】:2017-02-18 07:21:37
【问题描述】:
Python 3.5 版
我正在尝试使用 json 作为格式进行 API 调用来配置设备。一些 json 会根据所需的命名而有所不同,因此我需要在字符串中调用一个变量。我可以使用旧样式 %s... % (variable) 完成此操作,但不能使用新样式 {}... .format(variable)。
失败的EX:
(Testing with {"fvAp":{"attributes":{"name":(variable)}}})
a = "\"app-name\""
app_config = ''' { "fvAp": { "attributes": { "name": {} }, "children": [ { "fvAEPg": { "attributes": { "name": "app" }, "children": [ { "fvRsBd": { "attributes": { "tnFvBDName": "default" }, } } ] } }, { "fvAEPg": { "attributes": { "name": "db" }, "children": [ { "fvRsBd": { "attributes": { "tnFvBDName": "default" }, } } ] } } ] } } '''.format(a)
print(app_config)
回溯(最近一次调用最后一次):文件“C:/...,第 49 行,在 '''.format('a') KeyError: '\n "fvAp"'
工作前:
a = "\"app-name\""
app_config = ''' { "fvAp": { "attributes": { "name": %s }, "children": [ { "fvAEPg": { "attributes": { "name": "app" }, "children": [ { "fvRsBd": { "attributes": { "tnFvBDName": "default" }, } } ] } }, { "fvAEPg": { "attributes": { "name": "db" }, "children": [ { "fvRsBd": { "attributes": { "tnFvBDName": "default" }, } } ] } } ] } } ''' % a
print(app_config)
如何使用str.format 方法使其工作?
【问题讨论】:
标签: python json python-3.x string-formatting