这个问题已经有了答案:
String formatting [str.format()] with a dictionary key which is a str() of a number
4个答案
我想使用python字符串的format()作为一个快速而脏的模板。但是,我要使用的dict具有整数的键(字符串表示)。一个简单的例子如下:

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

上述代码引发以下错误:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: tuple index out of range

是否可以进行上述操作?

最佳答案

我们已经确定它不起作用,但是解决方案如何:
虽然在这种情况下,str.format不起作用,但有趣的是,旧的%格式将起作用。不建议这样做,但您确实要求使用快速而脏的模板。

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

但请注意,这对整数键不起作用。
>>> '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 - 带有整数键的dict的python字符串格式(),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20677660/

10-12 22:17
查看更多