Python打印字符串对齐

时间:2018-12-16 12:48:06

标签: python

我正在Python中循环打印一些值。我当前的输出如下:

0  Data Count:  249   7348   249   4469   2768   261   20   126
1  Data Count:  288   11   288   48     2284   598   137      408 
2  Data Count:  808   999   808   2896   32739   138   202   678
3  Data Count:  140   26   140   2688   8054   884   433      987

我想让每一列中的所有值对齐,尽管某些字符/数字计数不同,以便于阅读。

其背后的伪代码如下:

for i in range(0,3): 

    print i, " Data Count: ", Count_A, " ", Count_B, " ", Count_C, " ", Count_D, " ", Count_E, " ", Count_F, " ", Count_G, " ", Count_H

提前感谢大家!

2 个答案:

答案 0 :(得分:5)

您可以使用格式字符串对正:

from random import randint

for i in range(5):
    data = [randint(0, 1000) for j in range(5)]
    print("{:5} {:5} {:5} {:5}".format(*data))

输出:

   92   460    72   630
  837   214   118   677
  906   328   102   320
  895   998   177   922
  651   742   215   938

根据format specification from Python docs

答案 1 :(得分:0)

对于% string formatting operator,在占位符中将输出的最小宽度指定为数据类型(the full format of a placeholder is %[key][flags][width][.precision][length type]conversion type)之前的数字。如果结果较短,则将其填充到指定的长度:

from random import randint

for i in range(5):
    data = [randint(0, 1000) for j in range(5)]
    print("%5d %5d %5d %5d %5d" % tuple(data))

给予:

  946   937   544   636   871
  232   860   704   877   716
  868   849   851   488   739
  419   381   695   909   518
  570   756   467   351   537

(从@andreihondrari's answer改编的代码)