2017-06-15 74 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'