【发布时间】:2020-01-06 21:41:26
【问题描述】:
如何对带有三引号的嵌套字典进行字符串格式化?
我有一个我正在使用的 api,它要求我的 data 字段以特定方式格式化。
values = """{
"profile": {
"census_tract": "41051003901",
"street_address": "123 N Fake Ave",
"city": "Portland",
"state": "OR",
"zip_code": "97203",
"lat": 45.0000,
"lon": -122.00000
}
}"""
我想做一些类似的事情
{
"profile": {
"census_tract": "{0}",
"street_address": "{1}",
"city": "{2}",
"state": "{3}",
"zip_code": "{4}",
"lat": {5},
"lon": {6}
}
}
"""
print(values.format(in_census_tract, in_street_address, in_city, in_state, in_zip, in_lat, in_long))
我得到的不是格式正确的字符串:
'\n "profile"'
唯一有效的东西真的很丑......
a = """
{
"profile": {"""
b = ''' "census_tract": "{0}",
"street_address": "{1}",
"city": "{2}",
"state": "{3}",
"zip_code": "{4}",
"lat": {5},
"lon": {6}
'''
c = """
}
}
"""
values = a + b.format(in_census_tract, in_street_address, in_city, in_state, in_zip, in_lat, in_long) + c
【问题讨论】:
-
不要手动构建 JSON。构建 Python 数据结构,然后使用 the
jsonmodule 将其转换为 JSON。这有很多好处,但其中之一就是将动态值放入数据中将变得微不足道。
标签: python string dictionary nested formatting