当我们需要使用python连接数据库,拼接形成sql代码时,就需要灵活使用拼接字符串功能了,下面讲几种常用到的拼接字符串方法
拼接方式
1、简单拼接
a='select userid'
b='createtime'
print(a+','+b)
select userid,createtime
2、join拼接
c=[a,b]
print(','.join(c))
select userid,createtime
当有多个字段需要拼接时,使用join方式效率更快,例:
str=['you','are','a','handsome','boy']
p=''
for s in str:
p += s
p += ' '
print (p)
youareahandsomeboy
使用p += s方式,每循环一次就要形成一个新的字符串对象,最好的方式是直接将它们串联起来:
print (' '.join(str))
3、format拼接
以前,一般使用的都是’%s’,’%d’方式来代替字符串
#%s 格式化字符串
#%d 指的是整型
#%f 浮点型 只是%f时表示原值,默认是小数点后5位数
#%8.2f表示小数点后面精确到2位,总长度8位数,包括小数点,不够左侧补空格
print ('select %s,%d as cnt,%f as capital'%('userid',343,8765.938))
select userid,343 as cnt,8765.938000 as capital
Python2.6 开始,新增了一种格式化字符串的函数 str.format(),它增强了字符串格式化的功能。
# 1. {} 充当占位符
str = 'you are a {} {}'.format('handsome','boy')
print (str)
---------
you are a handsome boy
# 2. {[index]} 按索引位置填充 .format([0]=value1, [1]= value1},)
str1 = 'you are a {0} {1}'.format('handsome','boy')
str2 = 'you are a {1} {0}'.format('handsome','boy')
print(str1)
print(str2)
---------
you are a handsome boy
you are a boy handsome
# 3. {[keyword]}
str = 'you are a {a} {b}'.format(a='handsome',b='boy')
print (str)
---------
you are a handsome boy
# 4. {[keyword,index]} keyword 放在最后
str = 'you are a {1} {a} {0} {b}'.format('---','***',a='handsome',b='boy')
print (str)
---------
you are a *** handsome --- boy
#5. format 参数类型不限,当为元祖,列表,集合,字典时输出
str = 'you are a {a}'.format(a=['handsome','boy'])
print (str)
---------
you are a ['handsome', 'boy']
# 6. 作为函数使用
select_sql = 'select {1},{0} from {2}'.format
sql = select_sql('userid','name','xxx')
print(sql)
---------
select name,userid from xxx