我想使用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'
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)