为什么不是';t方法格式化Python字典键缩进?
由于某些原因,格式化字典键的方法仅在指定大于4的宽度后才开始缩进。知道为什么吗为什么不是';t方法格式化Python字典键缩进?,python,Python,由于某些原因,格式化字典键的方法仅在指定大于4的宽度后才开始缩进。知道为什么吗 for i in range(10): print({'{0:>{1}}'.format('test',i):12}, "should be indented", i) 输出: {'test': 12} should be indented 0 {'test': 12} should be indented 1 {'test': 12} should be indented 2 {'test': 12
for i in range(10):
print({'{0:>{1}}'.format('test',i):12}, "should be indented", i)
输出:
{'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
另外,当我试图将带有缩进键的字典输出到文本文档时,缩进并不一致。例如,当我指定10个字符的恒定缩进宽度时,整个输出的缩进不一致 这与dict键无关,数字4也没有什么特别之处;它恰好是字符串的长度
“test”
如果您说整个块应该右对齐到至少{1}
个字符的总长度,包括您作为{0}
传递的字符串。因此,如果{1}
是6
,而{0}
是“test”
,则字符串将填充两个空格,总长度为6
In [11]: "{0:>{1}}".format("test", 6)
Out[11]: ' test'
这与str.rjust
的功能类似:
In [12]: "test".rjust(6)
Out[12]: ' test'
如果您想要一个独立于字符串原始长度的常量填充,例如,可以使用字符串乘法,或者使用更复杂的格式字符串,在放入实际字符串之前将空字符串填充到某个给定长度
In [14]: " " * 6 + "test"
Out[14]: ' test'
In [15]: "{2:{1}}{0}".format("test", 6, "")
Out[15]: ' test'