在字典中格式化字符串

时间:2019-02-11 10:45:39

标签: python

我有一个看起来像这样的字符串

 payload = "{{\n  \n  \"task\" : \"videoFaceMatch\",  \n  \"essentials\":{\n  \n  \t\"video\" :\"{}\",\n  \t\"matchImage\" :\"{}\"\n  }\n}}".format(video_url, image)
print(payload)

如您所见,我正在尝试格式化此字符串,因此我添加了另外一组开括号和闭括号。但是当我运行此字符串时,我得到了

Traceback (most recent call last):
  File "video_match_output.py", line 12, in <module>
    payload = "{{\n  \n  \"task\" : \"videoFaceMatch\",  \n  \"essentials\":{\n  \n  \t\"video\" :\"{}\",\n  \t\"matchImage\" :\"{}\"\n  }\n}}".format(video_url, image)
KeyError: '\n  \n  \t"video" ' 

任何建议都会非常有帮助,谢谢。

这是所需的输出-

    payload = "{\n  \n  \"task\" : \"videoFaceMatch\",  \n  \"essentials\":{\n  \n  \t\"video\" :\"https://tech/api/files/89083/download/GaQuEpoDoWFh8u5HIWBmNIMgsIE58mCUHXVAOGBnU0lmC9HYHe.blob\",\n  \t\"matchImage\" :\"tech/api/files/5860111/download/VsZU1fWulpbsZ1c1zUmF28EhRT3OH1XpHphilaLQRF2E67Tb76.png\"\n  }\n}"

2 个答案:

答案 0 :(得分:2)

使用

payload = "{{\n  \n  \"task\" : \"videoFaceMatch\",  \n  \"essentials\":{{\n  \n  \t\"video\" :\"{}\",\n  \t\"matchImage\" :\"{}\"\n  }}\n}}".format("video_url", "image")
print(payload)

输出:

{

  "task" : "videoFaceMatch",  
  "essentials":{

    "video" :"video_url",
    "matchImage" :"image"
  }
}

答案 1 :(得分:2)

OP:由于在其中添加了另外一组开括号和闭括号。但是当我运行它时,我得到了

不是在之前,但在每个不应该出现的地方:

video_url = "http://www.video-url.com"
image = "image_sample.jpg"
payload = "\n  \n  \"task\" : \"videoFaceMatch\",  \n  \"essentials\":{{\n  
\n  \t\"video\" :\"{}\",\n  \t\"matchImage\" :\"{}\"\n  }}\n".format(video_url, image)
print(payload)

# or if you're trying to dump JSON:
print("\nPrinting through JSON..\n")

import json
mydict = {"payload": payload}
print(json.dumps(mydict))

输出:

  "task" : "videoFaceMatch",  
  "essentials":{      
    "video" :"http://www.video-url.com",
    "matchImage" :"image_sample.jpg"
  }

Printing through JSON..

{
 "payload": "\n  \n  \"task\" : \"videoFaceMatch\",  \n  \"essentials\":{\n 
 \n  \t\"video\" :\"http://www.video-url.com\",\n  \t\"matchImage\" :\"image_sample.jpg\"
 \n  }\n"
}