ghostmansd
ghostmansd

Reputation: 3455

Python's pretty printing of matrix

I have to print several rows of data and do it good. I can do it with C++ changing parameters of std::cout, but I can't understand how I can do it with Python. For example, I have this:

row1 = [1, 'arc1.tgz', 'First', '15.02.1992']
row2 = [16, 'arc2modified.tgz', 'Second', 'today']
row3 = ['112', 'arc89.tgz', 'Corrupted', 'unknown']

I want to print text like this:

1    arc1.tgz          First      15.02.1992
16   arc2modified.tgz  Second     today
112  arc89.tgz         Corrupted  unknown

It seems that it would be a clever idea to put it in one list and then count symbols in each string and then add spaces, but I'd like to know if there is more clever way to do it.

The main problem is that I can use only default Python's modules. Is there any possibility to do it? Thanks a lot!

Upvotes: 2

Views: 3331

Answers (1)

David Robinson
David Robinson

Reputation: 78590

my_matrix = [row1, row2, row3]
print "\n".join(["\t".join(map(str, r)) for r in my_matrix])

ETA: My original answer missed that you wanted each column to be of a fixed width, using padded spaces (rather than tabs). It also looks like you want exactly two spaces between the longest datum and the next column. In that case, it can be done as follows (note that string is a built-in, default Python module):

import string

max_lens = [max([len(str(r[i])) for r in my_matrix])
                for i in range(len(my_matrix[0]))]

print "\n".join(["".join([string.ljust(str(e), l + 2)
                for e, l in zip(r, max_lens)]) for r in my_matrix])

Upvotes: 9

Related Questions