【问题标题】:Python: String formatting on nested dictionary with tripple quoutesPython:带有三引号的嵌套字典上的字符串格式
【发布时间】: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

【问题讨论】:

标签: python string dictionary nested formatting


【解决方案1】:

啊,我明白了

所以我会做以下事情

tract = "41051003901"
street_address = "123 N Fake Ave"
city = "Portland"
state = "OR"
zipcode = "97203"
lat = 45.555551
long = -122.111111


values = {
    "profile": {
      "census_tract": tract,
      "street_address": street_address,
      "city": city,
      "state": state,
      "zip_code": zipcode,
      "lat": lat,
      "lon": long
    }
  }

dumper = json.dumps(values, indent=4)

print(dumper)

【讨论】:

    猜你喜欢
    • 2022-11-21
    • 2021-11-21
    • 2021-11-10
    • 2019-05-10
    • 1970-01-01
    • 1970-01-01
    • 2020-05-11
    • 2021-01-22
    • 1970-01-01
    相关资源
    最近更新 更多