首页 > 解决方案 > printf style "%0*d" % (m, n) -- 如果使用映射键,等效形式是什么 ("%???d" % { "width": m, "num": n })

问题描述

我需要格式化涉及相当多变量的长行,所以我使用映射键样式格式。(我个人不喜欢str.format()。:)

我尝试了很多,但未能找出正确的语法应该是什么。


使用元组参数它可以正常工作:

>>> width = 6
>>> num = 123
>>>
>>> '%0*d' % (width, num)
'000123'

我无法弄清楚如何使用 dict 参数来做到这一点:

>>> '%(width)0*d' % dict(width=width, num=num)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: not enough arguments for format string
>>>
>>> '%(width)(num)0*d' % dict(width=width, num=num)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: unsupported format character '(' (0x28) at index 8
>>>
>>> '%(width)0*(num)d' % dict(width=width, num=num)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: not enough arguments for format string

现在我正在使用一些解决方法。只是好奇这是可能的还是根本不支持。

标签: pythonpython-3.x

解决方案


事实证明它不受支持。在The Python Library Reference中找到了这个(见最后一句话):

当正确的参数是字典(或其他映射类型)时,字符串中的格式必须在字符之后立即插入到该字典中的带括号的映射键'%'。映射键从映射中选择要格式化的值。例如:

>>> print('%(language)s has %(number)03d quote types.' %
...       {'language': "Python", "number": 2})
Python has 002 quote types.

在这种情况下*,格式中不能出现说明符(因为它们需要顺序参数列表)。


推荐阅读