2010-05-17 81 views
17

格式化字符串時,我的字符串可能包含模數"%",我不希望轉換。作爲解決方法,我可以將字符串轉義並將每個"%"更改爲"%%"當字符串包含「%s」而沒有轉義時,Python字符串格式化

例如,

'Day old bread, 50%% sale %s' % 'today!' 

輸出:

'Day old bread, 50% sale today' 

但有任何替代逃逸?我希望使用一個字典可以讓Python忽略任何非關鍵字轉換。
例如,

'Day old bread, 50% sale %(when)s' % {'when': 'today'} 

但是Python仍然認爲第一模%,並給出了:

TypeError: not enough arguments for format string 
+2

轉義%不是一種解決方法,它是一種記錄和官方的方式。 – SilentGhost 2010-05-17 07:41:53

回答

22

你可以(也應該),而不是使用new string .format() method(如果你有Python的2.6或更高版本):

"Day old bread, 50% sale {0}".format("today") 

The manual can be found here

該文檔還表示,舊的%格式將最終從語言中刪除,但這肯定需要一些時間。新的格式化方法更強大,所以這是一件好事。

+0

除非你想打印「{{0}} = {0}」。format(「今天」),那麼你不會喜歡把花括號加倍。 :^) – 2010-05-18 01:27:32

+0

@MarkTolonen Ugg,我特意來到了這裏,希望能夠找到「{{0}}」格式(...)問題的解決方案...... – KSletmoe 2013-08-02 01:13:41

2

不是真的 - 你逃跑的跡象%是一分錢一分貨使用字符串格式化的價格。您可以使用字符串連接:'Day old bread, 50% sale ' + whichday如果有幫助...

+0

對於我需要支持Python 2.5或之前的版本,這是我將使用的方法。 – 2010-05-17 17:23:26

2

將'%'轉義爲'%%'不是解決方法。如果您使用字符串格式來表示'%'符號的方式。如果你不想要那樣,你總是可以這樣做:

print "Day old bread, 50% sale " + "today" 

例如,不使用格式。

請注意,使用字符串連接時,請確保該變量是一個字符串(而不是例如None)或使用str(varName)。否則,你會得到'不能連接str和NoneType'的東西。

2

您可以使用正則表達式由%%,其中%後面沒有(

def format_with_dict(str, dictionary): 
    str = re.sub(r"%([^\(])", r"%%\1", str) 
    str = re.sub(r"%$", r"%%", str) # There was a % at the end? 
    return str % dictionary 

這種方式來代替%:

print format_with_dict('Day old bread, 50% sale %(when)s', {'when': 'today'}) 

將輸出:

日齡麪包,今日出售50%

此方法對於避免「格式字符串的參數不足」錯誤很有用。