Python中字串格式化:%和format
阿新 • • 發佈:2019-01-03
Python2.6推出了[str.format()]方法,和原有的%格式化方式有小小的區別。那個方法更好?
-
下面的方法有同樣的輸出,它們的區別是什麼?
#!/usr/bin/python sub1 = "python string!" sub2 = "an arg" a = "i am a %s" % sub1 b = "i am a {0}".format(sub1) c = "with %(kwarg)s!" % {'kwarg':sub2} d = "with {kwarg}!".format(kwarg=sub2) print a # "i am a python string!"
-
另外在Python中格式化字串什麼時候執行?例如如果我的loggin的優先順序設定為高,那麼我還能用
%
操作符嗎?如果是這樣的話,有什麼方法可以避免嗎?log.debug("some debug info: %s" % some_info)
第一個問題:
format
在許多方面看起來更便利。你可以重用引數,但是你用%
就不行。最煩人的是%
它無法同時傳遞一個變數和元組。你可能會想下面的程式碼不會有什麼問題:
"hi there %s" % name
但是,如果name
恰好是(1,
2, 3)
,它將會丟擲一個TypeError
異常。
>>> name = (1, 2, 3)
>>> "hi there %s" % name
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: not all arguments converted during string formatting
>>>
為了保證它總是正確的,你必須這樣做:
>>> "hi there %s" % (name,) # 提供一個單元素的陣列而不是一個引數
'hi there (1, 2, 3)'
>>>
但是有點醜,format
就沒有這些問題。你給的第二個問題也是這樣,format
好看多了。
你為什麼不用它?
- 不知道它(在讀這個之前)
- 為了和Python2.5相容
第二個問題:
字串格式和其他操作一樣發生在它們執行的時候。Python是非懶惰語言,在函式呼叫前執行表示式,所以在你的log.debug
例子中,"some
debug info: %s"%some_info
將會先執行,先生成"some debug info: roflcopters are active"
,然後字串將會傳遞給log.debug()
。