亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Python字符串格式:%vs. .format

Python字符串格式:%vs. .format

Python字符串格式:%vs. .formatPython 2.6引入了該str.format()方法,其語法與現有%運算符略有不同。哪種情況更好,哪種情況更好?以下使用每種方法并具有相同的結果,那么有什么區別?#!/usr/bin/pythonsub1 = "python string!"sub2 = "an arg"a = "i am a %s" % sub1b = "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!"print b    # "i am a python string!"print c    # "with an arg!"print d    # "with an arg!"此外,何時在Python中發生字符串格式化?例如,如果我的日志記錄級別設置為HIGH,我仍然會執行以下%操作嗎?如果是這樣,有沒有辦法避免這種情況?log.debug("some debug info: %s" % some_info)
查看完整描述

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()。


查看完整回答
反對 回復 2019-05-28
?
繁星淼淼

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)   


print


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


查看完整回答
反對 回復 2019-05-28
?
萬千封印

TA貢獻1891條經驗 獲得超3個贊

假設您正在使用Python的logging模塊,您可以將字符串格式化參數作為參數傳遞給.debug()方法,而不是自己進行格式化:

log.debug("some debug info: %s", some_info)

這避免了格式化,除非記錄器實際記錄了一些東西。


查看完整回答
反對 回復 2019-05-28
  • 4 回答
  • 0 關注
  • 898 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號