str.format
是否自动编号, while string.Formatter
才不是。
修改__init__
并压倒一切get_value
会成功的。
def __init__(self):
super(CustFormatter, self).__init__()
self.last_number = 0
def get_value(self, key, args, kwargs):
if key == '':
key = self.last_number
self.last_number += 1
return super(CustFormatter, self).get_value(key, args, kwargs)
顺便说一句,上面的代码并不严格模仿str.format
行为。str.format
如果我们将自动编号与手动编号混合在一起,则会抱怨,但上面没有。
>>> '{} {1}'.format(1, 2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: cannot switch from automatic field numbering to manual field specification
>>> '{0} {}'.format(1, 2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: cannot switch from manual field specification to automatic field numbering