我終於從%
切換到我的2.x代碼中的.format()
字符串格式化運算符,以便將來更容易遷移到3.x。發現不僅%
風格的格式保留在Py3中,而且在標準庫代碼中被廣泛使用,這有點令人驚訝。這似乎是合乎邏輯的,因爲編寫'(%s)' % variable
比'({})'.format(variable)
短一些,可能更容易理解。但我仍然懷疑。在代碼中使用兩種方法是否合適(pythonic?)? 謝謝。Python 3:使用%s和.format()
24
A
回答
24
Python 3.2文檔說,%
最終會消失。
http://docs.python.org/3.2/tutorial/inputoutput.html#old-string-formatting
由於
str.format()
是相當新的,大量的Python代碼仍然使用%
操作。但是,由於這種舊格式的格式最終將從語言中刪除,因此str.format()
應該一般應使用 。
但作爲@regilero says,句子是從3.3消失了,這可能表明,它實際上並不是這樣。有一些對話here表明同樣的事情。
作爲Python 3.4 the paragraph 7.1.1讀取:
%運算符也可用於字符串格式。它將 左邊的參數解釋爲很像sprintf()樣式的格式字符串,將 應用於正確的參數,並返回 此格式操作產生的字符串。
-2
「%s」 爲現在的 「{}」,所以insted的添加%s與替換它的{},你會想將變量添加到字符串。
def main():
n="Python 3.+"
l="looks nice"
f="does not look practical."
print("This seems to be the new way {}".format(n)\
+ "will be working, rather than the ' % ',{} but {}".format(l,f))
main()
#In comparison to just injecting the variable
輸出無視他們是爲了說明原因
引號「這似乎是新路‘的Python 3 +’ 會工作,而不是「%;,‘看起來不錯’但「看起來不太實際」。「
+5
爲此答案添加一些解釋。 – Andrei
相關問題
- 1. Python 3 - [s for s in subsets(S)] and yield
- 2. Python,.format()和UTF-8
- 3. Python:嘗試使用「{} .replace()」.format()
- 4. Python的 - 多行用的raw_input或.format%s的
- 5. errors.full_messages format in rails 3
- 6. Tkinter的ListBox和使用.format
- 7. 當使用.format爲psycopg2它讀取它作爲列名,但使用與psycopg2巨蟒-3的.format在使用%
- 8. Python 3.5.2 .format()
- 9. Python .format - 錯誤
- 10. 的Python - .format()
- 11. 使用帶UTF-8字符串的boost :: format%s說明符
- 12. 「%s」%格式與「{0}」。format()vs「?」格式
- 13. Select statement with 2 case case/s format
- 14. 在HTML中使用Python變量/ .format()
- 15. 如何正確使用Python .format()?
- 16. 串聯字符串:str + str或「{:s} {:s}」。format()?
- 17. python的「.format」函數
- 18. python字符串格式化使用.format和變量
- 19. 錯誤使用「.format」
- 20. Apache-Error:[file「apache2_util.c」] [line 271] [level 3] [client%s] ModSecurity:%s%s [uri「%s」]%s
- 21. 使用python 3
- 22. Python 2.7:%d,%s和float()
- 23. 多行.format()方法的變量組在Python 3
- 24. 使用.format用繩子dictonary
- 25. 。Python中的.format()功能
- 26. Python字符串.format(*變量)
- 27. 多行參數Python的.format
- 28. Android-如何區分Galaxy S-3和Galaxy S-4佈局?
- 29. OpenLayers 3 Reload Layer(s)
- 30. Understanding Rails 3's respond_with
'%'格式化速度稍快。但是,如果你正在做很多重要的字符串格式,那麼你可能還有其他更重要的問題。 –