You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python格式化含原生{}的C代码模板时,如何保留原大括号?

在Python的str.format()中转义原生大括号的方法

要解决这个问题很简单——把你想保留的原生大括号写成双大括号{{和}}就可以了。Python的str.format()方法会自动把{{解析成单个的{,}}解析成单个的},同时不会把它们当成变量占位符处理。

为什么会报错?

你遇到的KeyError是因为模板里的单个{被format()当成了变量占位符的起始标记,它会尝试读取后面的内容作为变量名去settings字典里查找,但后面的内容是\n and later there is a ,显然不存在对应的key,所以就抛出了错误。

修改后的示例代码

template = """
Here is some text
Here is something to insert {name}
And here is a {{ and later there is a }}
"""
settings = {'name': "John"}
print( template.format(**settings) )

运行结果

Here is some text
Here is something to insert John
And here is a { and later there is a }

这种转义方式是Python官方文档明确支持的,不管是单独的大括号还是成对的(比如你想输出{example}这种内容,只需要写成{{example}})都能完美处理。

内容的提问来源于stack exchange,提问作者meddle0106

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 10:47:37