本文介绍了python string格式()与dict与整数键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Python字符串的格式()作为一个快速而肮脏的模板。但是,我想使用的 dict 具有整数的(字符串表示)的键。一个简化的例子如下:

I would like to use Python string's format() to act as a quick and dirty template. However, the dict that I would like to use has keys which are (string representations) of integers. a simplified example follows:

s = 'hello there {5}'
d = {'5': 'you'}
s.format(**d)

上述代码抛出以下错误:

the above code throws the following error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: tuple index out of range

是否可以执行上述? p>

is it possible to do the above?

推荐答案

我们已经确定它将无法正常工作,但解决方案如何:

We've established that it won't work, but how about a solution:

虽然 str.format 在这种情况下不起作用,但是,旧的格式化将很有趣。不建议这样做,但是您确实要求提供一个简单肮脏的模板。

Although str.format won't work in this case, funnily enough the old % formatting will. This is not recommended, but you did ask for a quick and dirty template.

>>> 'hello there %(5)s' % {'5': 'you'}
'hello there you'

请注意,这不会对整数键有效。

Do note though that this won't work for integer keys.

>>> 'hello there %(5)s' % {5: 'you'}

Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    'hello there %(5)s' % {5: 'you'}
KeyError: '5'

这篇关于python string格式()与dict与整数键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 04:44