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

Python字符串格式化中转义大括号的替代方案(SQL含JSON场景)

解决SQL查询中JSON大括号与.format()冲突的替代方案

给你几个不用转义大括号就能解决这个问题的办法:

1. 用replace()替代.format()

把需要替换的内容用特殊占位符(比如%xxx%这类不会和SQL语法冲突的标记)标记,之后用字符串的replace()方法完成替换,完全避开大括号的问题。

示例代码:

# 先把要替换的部分用自定义占位符标记
query = 'SELECT {"Success":true, "Message":"ErrorCode"}, %TARGET_COL%, col2 FROM Table1'
# 执行替换
final_query = query.replace("%TARGET_COL%", "new_col1")

2. 使用string.Template模板类

Python的string模块里的Template类支持用$作为占位符,不会和SQL里的大括号冲突,适合这种场景。

示例代码:

from string import Template

# 用$作为占位符定义模板
query_template = Template('SELECT {"Success":true, "Message":"ErrorCode"}, $col1, col2 FROM Table1')
# 替换占位符
final_query = query_template.substitute(col1="new_col1")

3. 临时替换大括号再还原

如果一定要用.format(),可以先把SQL里的JSON大括号临时替换成其他不冲突的字符,执行.format()后再替换回来:

示例代码:

query = 'SELECT {"Success":true, "Message":"ErrorCode"}, {target_col}, col2 FROM Table1'
# 先把JSON里的大括号换成临时标记
temp_query = query.replace("{", "@@{").replace("}", "@@}")
# 执行format替换
formatted_query = temp_query.format(target_col="new_col1")
# 还原大括号
final_query = formatted_query.replace("@@{", "{").replace("@@}", "}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 15:52:17