python - 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?
解决方案
您应该通过将它们加倍来逃避文字大括号:
json_data_resp = '{{"error":false,"code":"{0}","mac":"{1}","message":"Device configured successfully"}}'.format(activation_code, macaddress)
格式字符串语法摘录:
格式字符串包含用大括号括起来的“替换字段”
{}
。大括号中未包含的任何内容都被视为文字文本,它会原封不动地复制到输出中。如果需要在文字文本中包含大括号字符,可以通过加倍:{{
和}}
.
推荐阅读
- c# - 单击按钮从 asp .net MVC Web 应用程序打开 IOS 应用程序
- html - 如何定位 html 元素类名称而不是元素?
- python - 使用 mock.patch 模拟函数内部的变量
- html - 图像大小未重新调整以适应 flexbox
- javascript - Discord 音乐机器人由于某种原因停止工作
- c++ - 使用模板时:错误:没有匹配的构造函数用于初始化
- windows - 在 Windows 上从 Apache CGI 运行 gswin64c
- python - ValueError:输入 0 与层 lstm_15 不兼容:预期 ndim=3,发现 ndim=2
- ruby-on-rails - 为什么从路由中删除索引后 POST 的帮助程序路径会发生变化?
- python - 如何在烧瓶应用程序中正确存储全局变量