首页 > 解决方案 > Format on python string gives error

问题描述

In python, I'm trying to create a string by format()

json_data_resp = '{"error":false,"code":"{0}","mac":"{1}","message":"Device configured successfully"}'.format(activation_code, macaddress)

When I execute this code, it gives me an error like so:

KeyError: '"error"'

What is it that I'm doing incorrectly?

标签: pythonformat

解决方案


您应该通过将它们加倍来逃避文字大括号:

json_data_resp = '{{"error":false,"code":"{0}","mac":"{1}","message":"Device configured successfully"}}'.format(activation_code, macaddress)

格式字符串语法摘录:

格式字符串包含用大括号括起来的“替换字段” {}。大括号中未包含的任何内容都被视为文字文本,它会原封不动地复制到输出中。如果需要在文字文本中包含大括号字符,可以通过加倍: {{}}.


推荐阅读