如何將 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)

輸出

但這樣會引發 TypeError。若要保證它總是列印,你需要將其作為單個引數元組提供,如下 −

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

每次記住此類注意事項都不容易且可能導致漏洞。 .format 沒有這些問題。比較而言,format 也非常乾淨。

更新於: 2020 年 2 月 19 日

202 次瀏覽

開啟您的 職業生涯

透過完成課程並獲得認證

開始
廣告
© . All rights reserved.