Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to print a table with delimiters in Python

I want to print a table mixed with string and float values, as tab delimited output printout. Sure I can get the job done:

>>> tab = [['a', 1], ['b', 2]]
>>> for row in tab:
...     out = ""
...     for col in row:
...             out = out + str(col) + "\t"
...     print out.rstrip()
... 
a   1
b   2

But I have a feeling there is a better way to do it in Python, at least to print each row with specified delimiter, if not the whole table. Little googling (from here) and it is already shorter:

>>> for row in tab:
...     print "\t".join([str(col) for col in row])
... 
a   1
b   2

Is there still a better, or more Python-ish, way to do it?

like image 357
ketorin Avatar asked Nov 29 '22 21:11

ketorin


2 Answers

Your shorter solution would work well as something quick and dirty. But if you need to handle large amounts of data, it'd be better to use csv module:

import sys, csv
writer = csv.writer(sys.stdout, delimiter="\t")
writer.writerows(data)

The benefit of this solution is that you may easily customize all aspects of output format: delimiter, quotation, column headers, escape sequences...

like image 128
Alexander Lebedev Avatar answered Dec 05 '22 07:12

Alexander Lebedev


I don't think it's going to get much better than your second code snippet... maybe, if you really want,

print "\n".join("\t".join(str(col) for col in row) for row in tab)
like image 21
David Z Avatar answered Dec 05 '22 07:12

David Z