简体   繁体   中英

Python print string alignment

I am printing some values in a loop in Python. My current output is as follows:

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

What I'd like is for all values in each column to align, despite differing character/number counts in some, to make it easier to read.

The pseudo code behind this is as follows:

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

Thanks in advance everyone!

You could use format string justification:

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))

output:

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

According to the format specification from Python docs

With the % string formatting operator , the minimum width of output is specified in a placeholder as a number before the data type ( the full format of a placeholder is %[key][flags][width][.precision][length type]conversion type ). If the result is shorter, it will be left-padded to the specified length:

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))

gives:

  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

(code adapted from @andreihondrari's answer )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM