4 回答

TA貢獻1808條經驗 獲得超4個贊
回答你的第一個問題...... .format
在許多方面似乎更復雜。令人討厭的%
是它如何能夠采用變量或元組。您認為以下內容始終有效:
"hi there %s" % name
然而,如果name
恰好是(1, 2, 3)
,它會拋出一個TypeError
。為了保證它始終打印,您需要這樣做
"hi there %s" % (name,) # supply the single argument as a single-item tuple
這只是丑陋的。.format
沒有那些問題。同樣在你給出的第二個例子中,這個.format
例子看起來更清晰。
你為什么不用它?
不知道它(我在讀這篇文章之前)
必須與Python 2.5兼容
要回答第二個問題,字符串格式化與任何其他操作同時發生 - 評估字符串格式化表達式時。并且Python不是一種懶惰的語言,在調用函數之前會對表達式求值,所以在你的log.debug
例子中,表達式"some debug info: %s"%some_info
將首先求值,例如"some debug info: roflcopters are active"
,然后傳遞給該字符串log.debug()
。

TA貢獻1775條經驗 獲得超11個贊
模數運算符(%)不能做的事情,afaik:
tu = (12,45,22222,103,6)
print '{0} {2} {1} {2} {3} {2} {4} {2}'.format(*tu)
結果
12 22222 45 22222 103 22222 6 22222
很有用。
另一點:format()作為一個函數,可以在其他函數中用作參數:
li = [12,45,78,784,2,69,1254,4785,984]
print map('the number is {}'.format,li)
from datetime import datetime,timedelta
once_upon_a_time = datetime(2010, 7, 1, 12, 0, 0)
delta = timedelta(days=13, hours=8, minutes=20)
gen =(once_upon_a_time +x*delta for x in xrange(20))
print '\n'.join(map('{:%Y-%m-%d %H:%M:%S}'.format, gen))
結果是:
['the number is 12', 'the number is 45', 'the number is 78', 'the number is 784', 'the number is 2', 'the number is 69', 'the number is 1254', 'the number is 4785', 'the number is 984']
2010-07-01 12:00:00
2010-07-14 20:20:00
2010-07-28 04:40:00
2010-08-10 13:00:00
2010-08-23 21:20:00
2010-09-06 05:40:00
2010-09-19 14:00:00
2010-10-02 22:20:00
2010-10-16 06:40:00
2010-10-29 15:00:00
2010-11-11 23:20:00
2010-11-25 07:40:00
2010-12-08 16:00:00
2010-12-22 00:20:00
2011-01-04 08:40:00
2011-01-17 17:00:00
2011-01-31 01:20:00
2011-02-13 09:40:00
2011-02-26 18:00:00
2011-03-12 02:20:00

TA貢獻1891條經驗 獲得超3個贊
假設您正在使用Python的logging
模塊,您可以將字符串格式化參數作為參數傳遞給.debug()
方法,而不是自己進行格式化:
log.debug("some debug info: %s", some_info)
這避免了格式化,除非記錄器實際記錄了一些東西。
添加回答
舉報