【发布时间】:2014-01-07 18:47:54
【问题描述】:
我想使用 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作为变量名,因为它会覆盖内置的str类。 -
如果密钥实际上是整数,
{[5]}会起作用。
标签: python string templates dictionary format