如何使用字串格式化在 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, ) 符號將單值元組與表示式區分開來。

更新於: 17-Jun-2020

771 瀏覽

開啟你的 職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.