如何比較 Python 字串格式化:% 和 .format?


% 可同時使用變數或元組。因此,你需要明確指出它需要執行的操作。例如,如果你嘗試按以下方式進行格式化 −

示例

my_tuple = (1, 2, 3)
"My tuple: %s" % my_tuple
You'd expect it to give the output:
My tuple: (1, 2, 3)

輸出

但它會丟擲一個型別錯誤。為確保它始終列印,你需要以以下形式提供一個單一的元組引數 −

"hi there %s" % (name,)   # supply the single argument as a single-item tuple

每次記住這些注意事項並非易事,而且可能會造成錯誤。 .format 沒有這些問題。相比之下, format 也很乾淨。

更新於:19-Feb-2020

202 次瀏覽

開啟你的 職業生涯

完成課程後獲得認證

開始
廣告
© . All rights reserved.