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

Python字符串格式化:如何用.format为变量添加单引号

解决方案

有两种简单的方法可以实现需求:

方法一:在format占位符前后添加单引号

直接在格式字符串里给{}包裹单引号,替换变量后就会自动带上单引号:

state = 'PA'
# 用转义单引号包裹占位符
sql_str = 'select * from table where "state" = \'{}\''.format(state)
# 或者用双引号定义外层字符串,可读性更好
sql_str = "select * from table where \"state\" = '{}'".format(state)

执行后sql_str的值就是:select * from table where "state" = 'PA'

方法二:使用f-string(Python3.6+)

f-string是更简洁的字符串格式化方式,给变量包裹单引号即可:

state = 'PA'
sql_str = f'select * from table where "state" = \'{state}\''
# 或者双引号版本
sql_str = f"select * from table where \"state\" = '{state}'"

注意:如果是在实际项目中操作数据库,直接用字符串拼接/格式化生成SQL存在SQL注入风险,建议使用数据库驱动提供的参数化查询功能(比如cursor.execute("select * from table where state = %s", (state,))这类写法),或者借助ORM框架来操作数据库。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 14:40:15