场景:使用python执行带有in的sql语句,对in中的句子进行参数化,如下所示:
select * from table where column in ('str1','str2'......)
由于不确定in中的参数有多少个,使用原来%s的方式就不能解决,这时候就需要使用str.format:
基本语法是通过 {} 和 : 来代替以前的 % 。
- format 函数可以接受不限个参数,位置可以不按顺序。
>>>"{} {}".format("hello", "world") # 不设置指定位置,按默认顺序
'hello world'
>>> "{0} {1}".format("hello", "world") # 设置指定位置
'hello world'
>>> "{1} {0} {1}".format("hello", "world") # 设置指定位置
'world hello world'
- 也可以设置参数:
>>> "我的名字是{name},我{age}岁了!".format(name='Narido',age=6)
'我的名字是Narido,我6岁了!'
使用字典,字典前需要添加"**"
>>> "我的名字是{name},我{age}岁了!".format(**{'name':'Narido','age':6})
'我的名字是Narido,我6岁了!'
使用列表,如下0是必须要的:
>>> "我的名字是{0[0]},我{0[1]}岁了!".format(['Narido',6])
'我的名字是Narido,我6岁了!'
甚至,可以传入对象,如下0是可选的:
# coding: UTF-8
class Narido(object):
def __init__(self, name,value):
self.name = name
self.age = age
my_info = AssignValue('Narido',6)
print('我的名字是 {0.value},我{0.age}岁了'.format(my_info)) # "0" 是可选的
- 支持数字格式化,只需要添加":",其它语法见博客:Python基础之数据类型转换及格式化输出 如:
>>> print("{:.2f}".format(3.1415926));
3.14
- 如果想要输入{},可以使用{}进行转义,如下:
>>> "{}对应位置是{{0}}".format("test")
'test对应位置是{0}'
经过上面的系统学习,我们来解决最初的问题:
>>> "select * from fruits_info where fruits_name in ({})".format(",".join('"' + item + '"' for item in ['apple','pear']))
'select * from fruits_info where fruits_name in ("apple","pear")'
经过上面的学习,我发现,原来%也能解决:
>>> "select * from fruits_info where fruits_name in (%s)" % (",".join('"' + item + '"' for item in ['apple','pear']))
'select * from fruits_info where fruits_name in ("apple","pear")'
白学习了……算了,多一种参数化的方式吧!