如何使用字串格式化在 Python 中列印一個完整的元組?
在 Python 中使用舊式字串格式化,即 "" % (),如果百分號後面的內容是元組,Python 會嘗試將其分解,並將各個專案傳遞到字串中。例如,
tup = (1,2,3)
print("this is a tuple %s" % (tup))會給出以下輸出
TypeError: not all arguments converted during string formatting
這是由於上述原因造成的。如果您想要傳遞一個元組,您需要使用 (tup, ) 語法建立一個包裝元組。例如,
tup = (1,2,3)
print("this is a tuple %s" % (tup, ))會給出以下輸出
this is a tuple (1, 2, 3)
(tup, ) 符號將單值元組與表示式區分開來。
廣告
資料結構
計算機網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP