非模板字符串上的str.format静默忽略模板参数

时间:2014-07-29 11:37:05

标签: python string

>>> 'potato'.format(123)
'potato'
>>> 'potato'.format(kw='hello')
'potato'

我真的希望在这里提出一个异常,而不是默默地忽略模板。

为什么在python中允许这样做,哪种有效的用例更适合这种行为?

1 个答案:

答案 0 :(得分:1)

忽略额外的参数使格式更加灵活。请注意,这不是关于'非模板'字符串;如果你有占位符,额外的参数仍然被忽略

>>> 'potato {}'.format(123, 456)
'potato 123'
>>> 'potato {spam}'.format(spam=123, eggs=456)
'potato 123'

通过忽略额外的参数,您可以使用变量模板,选择一个,并传入所有可能的插值,或传入vars(self)以获得基于当前的灵活格式实例:

def __str__(self):
    return '<Foo object, spam={spam!r}, eggs={eggs!r}'.format(**vars(self))

无需担心您不会使用此特定模板的额外参数。