Line up columns of numbers (print output in table format)

Here is a simple, self-contained example that shows how to format variable column widths:

data=""'\
234 127 34 23 45567
23 12 4 4 45
23456 2 1 444 567'''

# Split input data by row and then on spaces
rows = [ line.strip().split(' ') for line in data.split('\n') ]

# Reorganize data by columns
cols = zip(*rows)

# Compute column widths by taking maximum length of values per column
col_widths = [ max(len(value) for value in col) for col in cols ]

# Create a suitable format string
format=" ".join(['%%%ds' % width for width in col_widths ])

# Print each row using the computed format
for row in rows:
  print format % tuple(row)

which outputs:

  234 127 34  23 45567
   23  12  4   4    45
23456   2  1 444   567

Leave a Comment