python3的字符串格式化


我們知道Python3.x引入了新的字符串格式化語法。

不同於Python2.x的


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


Python3.x是


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


'{0},{1}'.format('jack',22)

Out[32]: 'jack,22'


'{1},{0},{1}'.format('jack',22)

Out[33]: '22,jack,22'


'{name},{age}'.format(age=28,name='jack')

Out[35]: 'jack,28'


用MySQLdb時,需要用帶參數的cursor.execute(sql,param)語句來完成SQL操作。

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

其中param是一個元組,表示要插入的數據,元組中的各個元素即是數據庫中各列的值。

但是執行起來總是會拋出數據庫異常,錯誤信息:


【108900】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) 

 




print 會自動在行末加上回車,如果不需回車,只需在print語句的結尾添加一個逗號”,“,就可以改變它的行爲。


for i in range(0, 6):

    print(i,)


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章