【问题标题】:How to concatenate strings in Python using Format?如何使用 Format 在 Python 中连接字符串?
【发布时间】:2018-11-11 14:50:29
【问题描述】:

我想在我的 Payload 中发送动态数据,

payload = "{\r\n \"name\": \"{0}\",\r\n \"id\":\"{1}\"}".format(1,2)
*** KeyError: '\r\n "name"'

但是当我尝试添加静态值时,它工作正常:

payload = "{\r\n \"name\": \"just\",\r\n \"id\":\"32\"}"

如何添加动态数据?

提前致谢。

【问题讨论】:

    标签: python django python-3.x python-2.7 django-rest-framework


    【解决方案1】:

    这是因为第一个和最后一个括号。

    你必须逃脱{}

    "{{\r\n \"name\": \"{}\",\r\n \"id\":\"{}\"}}".format(1,2)
    

    【讨论】:

    • 我猜可能是因为虽然你回答了这个问题,但你也应该建议他们不要使用字符串格式来生成 JSON。
    【解决方案2】:

    使用 JSON 模块代替操作字符串中的 JSON。

    例如:

    import json
    payload = {"name": '',"id":''}
    payload["name"] = 1
    payload["id"] = 2
    
    payload = json.dumps(payload)
    print( payload )
    print( type(payload) )
    

    输出:

    {"name": 1, "id": 2}
    <type 'str'>
    

    【讨论】:

      【解决方案3】:

      您的问题是,当您使用format() 时,大括号字符是特殊的(因为{0}),需要通过加倍不特殊的大括号来进行转义:

      >>> payload = "{{\r\n \"name\": \"{0}\",\r\n \"id\":\"{1}\"}}".format("just",32)
      >>> payload
      '{\r\n "name": "just",\r\n "id":"32"}'
      

      【讨论】:

        【解决方案4】:

        问题来自您使用的 { 和 }。你应该把它们加倍:

        payload = "{{\r\n \"name\": \"{0}\",\r\n \"id\":\"{1}\"}}".format(1,2)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-03-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-12-15
          • 1970-01-01
          • 2019-04-27
          相关资源
          最近更新 更多