yee*_*379 17 python string format templates dictionary
我想使用Python字符串format()
作为一个快速和脏的模板.但是,dict
我想使用的是具有整数(字符串表示)的键.简化示例如下:
s = 'hello there {5}'
d = {'5': 'you'}
s.format(**d)
Run Code Online (Sandbox Code Playgroud)
上面的代码抛出以下错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: tuple index out of range
Run Code Online (Sandbox Code Playgroud)
可以做到以上几点吗?
Vol*_*ity 28
我们已经确定它不会起作用,但解决方案如何:
虽然str.format
在这种情况下不起作用,但有趣的是旧的%
格式化.这不是推荐的,但你确实要求快速而脏的模板.
>>> 'hello there %(5)s' % {'5': 'you'}
'hello there you'
Run Code Online (Sandbox Code Playgroud)
请注意,这不适用于整数键.
>>> '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'
Run Code Online (Sandbox Code Playgroud)
我喜欢扩展Formatter的想法,以便允许任意字段名称(整数,带冒号的字段名称等).实现可能如下所示:
import string, re
class QuFormatter(string.Formatter):
def _quote(self, m):
if not hasattr(self, 'quoted'):
self.quoted = {}
key = '__q__' + str(len(self.quoted))
self.quoted[key] = m.group(2)
return '{' + m.group(1) + key + m.group(3) + '}'
def parse(self, format_string):
return string.Formatter.parse(self,
re.sub(r'{([^}`]*)`([^}`]*)`([^}]*)}', self._quote, format_string))
def get_value(self, key, args, kwargs):
if key.startswith('__q__'):
key = self.quoted[key]
return string.Formatter.get_value(self, key, args, kwargs)
Run Code Online (Sandbox Code Playgroud)
用法:
d = {'5': 'you', '6': 'me', "okay":1, "weird:thing!": 123456}
print QuFormatter().format(
'hello there {`5`} {`6`:20s}--{okay}--{`weird:thing!`:20,d}',
**d)
Run Code Online (Sandbox Code Playgroud)
因此,反叛中的字段按字面意思处理.
请参阅此帖子以获取问题的答案.您似乎不能在格式字符串(docs链接)中使用由数字组成的字符串作为字典键.
如果您可以使用5以外的密钥,那么它将起作用:
my_string='hello there {spam:s}'
d={'spam': 'you'}
print my_string.format(**d) # Returns "hello there you"
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
31271 次 |
最近记录: |