views:

944

answers:

5

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?

+4  A: 

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)
David Zaslavsky
+12  A: 

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

Alex Lebedev
As it stands though, that solution will probably do many things you wouldn't expect. It will double-up quotes in your input, for example. Embedded quotes are treated by "quoting" the whole string, which may or may not be what you want.
Brian
(continued) If all that is desired is simple tab delmited data, with no danger of embedded tabs, the basic approach is probably easier to get right, rather than figuring the appropriate dialect to use with the csv module.
Brian
Excellent, cvs was exactly what I was looking for. I need to go through documentation, but I think the things I would not expect may very well be what I want anyway.
ketorin
+2  A: 
import sys
import csv

writer = csv.writer(sys.stdout, dialect=csv.excel_tab)
tab = [['a', 1], ['b', 2]]
writer.writerows(tab)
monowerker
`dialect` should be either `'excel-tab'` or `csv.excel_tab` but not `'csv.excel_tab'`
J.F. Sebastian
A: 

Please do not use concatanation because it creates a new string every time. cStringIO.StringIO will do this kind of job much more efficiently.

RommeDeSerieux
str.join is efficient already.
recursive
A: 

It depends on why you want to output like that, but if you just want to visually reference the data you might want to try the pprint module.

>>> import pprint
>>> for item in tab:
...     pprint.pprint(item, indent=4, depth=2)
...
['a', 1]
['b', 2]
>>>
>>> pprint.pprint(tab, indent=4, width=1, depth=2)
[   [   'a',
        1],
    [   'b',
        2]]
>>>
monkut