由于某种原因,格式化字典键的方法仅在指定宽度大于4后才开始缩进.任何想法为什么?
for i in range(10):
print({'{0:>{1}}'.format('test',i):12}, "should be indented", i)
Run Code Online (Sandbox Code Playgroud)
输出:
{'test': 12} should be indented 0
{'test': 12} should be indented 1
{'test': 12} should be indented 2
{'test': 12} should be indented 3
{'test': 12} should be indented 4
{' test': 12} should be indented 5
{' test': 12} should be indented 6
{' test': 12} should be indented 7
{' test': 12} should be indented 8
{' test': 12} should be indented 9
Run Code Online (Sandbox Code Playgroud)
此外,当我尝试将带有缩进键的字典输出到文本文档时,缩进不一致.例如,当我指定10个字符的常量缩进宽度时,缩进在输出中不一致.
这与dict键无关,4号也没有什么特别之处; 它恰好是你的字符串的长度"test".
有了{0:>{1}}你说的是整个块应该是右对齐至少总长度{1}的字符,包括你作为传递的字符串{0}.所以,如果{1}是6,并且{0}是"test",则该字符串被填充为两个空间,为6的总长度.
In [11]: "{0:>{1}}".format("test", 6)
Out[11]: ' test'
Run Code Online (Sandbox Code Playgroud)
这类似于str.rjust:
In [12]: "test".rjust(6)
Out[12]: ' test'
Run Code Online (Sandbox Code Playgroud)
如果你想要一个独立于字符串原始长度的常量填充,你可以,例如,使用字符串乘法,或者使用更复杂的格式字符串,在放入实际字符串之前将空字符串填充到某个给定的长度.
In [14]: " " * 6 + "test"
Out[14]: ' test'
In [15]: "{2:{1}}{0}".format("test", 6, "")
Out[15]: ' test'
Run Code Online (Sandbox Code Playgroud)