如何將 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 也非常乾淨。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP