Heim  >  Artikel  >  Backend-Entwicklung  >  Python3.x版本中新的字符串格式化方法

Python3.x版本中新的字符串格式化方法

WBOY
WBOYOriginal
2016-06-06 11:25:371126Durchsuche

我们知道Python3.x引入了新的字符串格式化语法。不同于Python2.x的

代码如下:


"%s %s "%(a,b) 


Python3.x是

代码如下:


"{0} {1}".format(a,b) 


今天我在用MySQLdb时,需要用带参数的

代码如下:


cursor.execute(sql,param) 


语句来完成SQL操作。被其他文章的陈旧说法给误导,用了

代码如下:


cursor.execute('insert into test values(%s,%s,%s)',param) 


其中param是一个元组,表示要插入的数据,元组中的各个元素即是数据库中各列的值。
但是执行起来总是会抛出数据库异常,错误信息:

代码如下:


【1064】You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near'(%s,%s,%s)'at line……(以下省略)。


其实只要改成这样就好:

代码如下:


cursor.execute('insert into test values({0},{1},{2})',param) 


实话说,Python3为了填上Python2的各坑导致了不向下兼容,使得学习Python3的成本提高了不少。但是为了不阻碍科技发展、社会进步,我还是毅然决然投身新版本……

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn