2017-06-15 37 views
0

我有喜歡KeyError異常在多個關鍵串插蟒蛇

In [5]: x = "this string takes two like {one} and {two}" 

In [6]: y = x.format(one="one") 
--------------------------------------------------------------------------- 
KeyError         Traceback (most recent call last) 
<ipython-input-6-b3c89fbea4d3> in <module>() 
----> 1 y = x.format(one="one") 

KeyError: 'two' 

一個問題我已經與被保存在配置文件中的許多鍵複合字符串。對於8個不同的查詢,它們都使用相同的字符串,但1個密鑰是不同的設置。我需要能夠替代該文件一鍵拯救字符串後,如:

"this string takes two like one and {two}" 

如何在使用format一次替換一個關鍵?謝謝

+0

你至少可以做'y = x.format(one =「one」,two =「{two}」)'但這可能不是最好的方法來處理它... – JohanL

+0

'y = x.replace('{one }','不管')'? – khelwood

回答

2

如果在字符串中的佔位符不具有任何格式規範,在Python 3,你可以使用str.format_map並提供映射,失蹤返回的字段名稱田:

class Default(dict): 
    def __missing__(self, key): 
     return '{' + key + '}' 
In [6]: x = "this string takes two like {one} and {two}" 

In [7]: x.format_map(Default(one=1)) 
Out[7]: 'this string takes two like 1 and {two}' 

如果你有格式規範,你就必須以子類string.Formatter並覆蓋一些方法,或切換到不同的格式化方法,如string.Template

+0

非常有趣的方法。 –

2

您可以通過花括號加倍逃脫{two}插值:

x = "this string takes two like {one} and {{two}}" 
y = x.format(one=1) 
z = y.format(two=2) 
print(z) # this string takes two like 1 and 2 

用不同的方式去爲template strings

from string import Template 

t = Template('this string takes two like $one and $two') 
y = t.safe_substitute(one=1) 
print(y) # this string takes two like 1 and $two 
z = Template(y).safe_substitute(two=2) 
print(z) # this string takes two like 1 and 2 

this answer是我之前模板字符串....)

+0

讓我們看看那個 – codyc4321

+2

它會導致長序列被逐位替換的問題... – JohanL

+0

由於某種原因,這在shell中工作,但當我嘗試運行服務器時發生了爆炸 – codyc4321

1

你可以repl王牌{two}通過{two}以後能進一步置換:

y = x.format(one="one", two="{two}") 

這容易在多個替代通道延伸,但它要求你給所有的鑰匙,在每次迭代。

3

我想string.Template你想要做什麼:

from string import Template 

s = "this string takes two like $one and $two" 
s = Template(s).safe_substitute(one=1) 
print(s) 
# this string takes two like 1 and $two 

s = Template(s).safe_substitute(two=2) 
print(s) 
# this string takes two like 1 and 2 
0

所有優秀的答案,我很快就會開始使用這個Template包。在這裏的默認行爲非常失望,不理解爲什麼字符串模板每次都需要傳遞所有的鍵,如果有3個鍵我看不到邏輯原因你不能傳遞1或2(但我也沒有知道如何編譯工作)

通過使用按鍵%s對我立即在配置文件替換項目,{key}解決我後來更換後的燒瓶服務器的執行

In [1]: issue = "Python3 string {item} are somewhat defective: %s" 

In [2]: preformatted_issue = issue % 'true' 

In [3]: preformatted_issue 
Out[3]: 'Python3 string {item} are somewhat defective: true' 

In [4]: result = preformatted_issue.format(item='templates') 

In [5]: result 
Out[5]: 'Python3 string templates are somewhat defective: true'