1

我有一个要打印的数字列表,如下所示:

          1
          1
          3
         11
         58
        451
      4 461
     49 957
    598 102
  7 437 910
 94 944 685

目前我通过以下丑陋的代码实现了这一点:

for count in counts:
    s = str(count)[::-1]
    s = ' '.join([s[i:i+3][::-1] for i in range(0,len(s),3)][::-1])
    print('{:>11}'.format(s))

无论如何,有没有format可以立即实现这一目标?我在文档中找不到任何内容。

4

1 回答 1

1

您可以在字符串格式化程序中使用千位分隔符并将其替换为您喜欢的内容,如下所示:

>>> nums = (1, 3, 11, 58, 451, 4461, 49957, 598102, 7437910, 94944685)
>>> for num in nums:
        print('{:>11,}'.format(num).replace(',', ' '))

          1
          3
         11
         58
        451
      4 461
     49 957
    598 102
  7 437 910
 94 944 685
于 2012-12-11T09:41:26.930 回答