2016-07-05 74 views
-1

出於某種原因,格式化字典鍵的方法僅在指定大於4的寬度後開始縮進。任何想法爲什麼?爲什麼不是方法格式化Python字典鍵的縮進?

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個字符的常量縮進寬度時,縮進在輸出中不一致。

回答

5

這與dict鍵沒有任何關係,對於數字4也沒有什麼特別之處;它恰好是你的字符串的長度"test"

隨着{0:>{1}}你說的是整個塊應該是右對齊至少{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' 
相關問題