string – Create nice column output in python

string – Create nice column output in python

Since Python 2.6+, you can use a format string in the following way to set the columns to a minimum of 20 characters and align text to right.

table_data = [
    [a, b, c],
    [aaaaaaaaaa, b, c], 
    [a, bbbbbbbbbb, c]
]
for row in table_data:
    print({: >20} {: >20} {: >20}.format(*row))

Output:

               a                    b                    c
      aaaaaaaaaa                    b                    c
               a           bbbbbbbbbb                    c
data = [[a, b, c], [aaaaaaaaaa, b, c], [a, bbbbbbbbbb, c]]

col_width = max(len(word) for row in data for word in row) + 2  # padding
for row in data:
    print .join(word.ljust(col_width) for word in row)

a            b            c            
aaaaaaaaaa   b            c            
a            bbbbbbbbbb   c   

What this does is calculate the longest data entry to determine the column width, then use .ljust() to add the necessary padding when printing out each column.

string – Create nice column output in python

I came here with the same requirements but @lvc and @Preets answers seems more inline with what column -t produces in that columns have different widths:

>>> rows =  [   [a,           b,            c,    d]
...         ,   [aaaaaaaaaa,  b,            c,    d]
...         ,   [a,           bbbbbbbbbb,   c,    d]
...         ]
...

>>> widths = [max(map(len, col)) for col in zip(*rows)]
>>> for row in rows:
...     print   .join((val.ljust(width) for val, width in zip(row, widths)))
...
a           b           c  d
aaaaaaaaaa  b           c  d
a           bbbbbbbbbb  c  d

Leave a Reply

Your email address will not be published. Required fields are marked *