25

Using python2.7, I'm trying to print to screen tabular data.

This is roughly what my code looks like:

for i in mylist:
   print "{}\t|{}\t|".format (i, f(i))

The problem is that, depending on the length of i or f(i) the data won't be aligned.

This is what I'm getting:

|foo |bar |
|foobo   |foobar  |

What I want to get:

|foo     |bar     |
|foobo   |foobar  |

Are there any modules that permit doing this?

0

6 Answers 6

32

It's not really hard to roll your own formatting function:

def print_table(table):
    col_width = [max(len(x) for x in col) for col in zip(*table)]
    for line in table:
        print "| " + " | ".join("{:{}}".format(x, col_width[i])
                                for i, x in enumerate(line)) + " |"

table = [(str(x), str(f(x))) for x in mylist]
print_table(table)
Sign up to request clarification or add additional context in comments.

4 Comments

For others' reference, I had to change the format string to "{0:{1}}" to get it to work properly.
Pylint complains about the * :(. It says "Used * or ** magic".
Note that this code may not perform correctly if the iterables in table contain any non-string objects, since the len will either not be defined, or may be incorrect. To fix that, change max(len(x) to max(len(str(x)).
Not really hard but certainly ugly and unnecessary.
25

For a more beautiful table, use the tabulate module:

Tabulate link

Example from the tabulate documentation:

>>> from tabulate import tabulate

>>> table = [["Sun",696000,1989100000],["Earth",6371,5973.6],
...          ["Moon",1737,73.5],["Mars",3390,641.85]]
>>> print(tabulate(table))
-----  ------  -------------
Sun    696000     1.9891e+09
Earth    6371  5973.6
Moon     1737    73.5
Mars     3390   641.85
-----  ------  -------------

1 Comment

Yeah, I used this one, and very simple to have a table like structure in just few lines of code!
23

There is a nice module for this in pypi, PrettyTable.

http://code.google.com/p/prettytable/wiki/Tutorial

http://pypi.python.org/pypi/PrettyTable/

$ pip install PrettyTable

Comments

9

You can try BeautifulTable. Here's an example:

>>> from beautifultable import BeautifulTable
>>> table = BeautifulTable()
>>> table.column_headers = ["name", "rank", "gender"]
>>> table.append_row(["Jacob", 1, "boy"])
>>> table.append_row(["Isabella", 1, "girl"])
>>> table.append_row(["Ethan", 2, "boy"])
>>> table.append_row(["Sophia", 2, "girl"])
>>> table.append_row(["Michael", 3, "boy"])
>>> print(table)
+----------+------+--------+
|   name   | rank | gender |
+----------+------+--------+
|  Jacob   |  1   |  boy   |
+----------+------+--------+
| Isabella |  1   |  girl  |
+----------+------+--------+
|  Ethan   |  2   |  boy   |
+----------+------+--------+
|  Sophia  |  2   |  girl  |
+----------+------+--------+
| Michael  |  3   |  boy   |
+----------+------+--------+

Comments

8
mylist = {"foo":"bar", "foobo":"foobar"}

width_col1 = max([len(x) for x in mylist.keys()])
width_col2 = max([len(x) for x in mylist.values()])

def f(ind):
    return mylist[ind]

for i in mylist:
    print "|{0:<{col1}}|{1:<{col2}}|".format(i,f(i),col1=width_col1,
                                            col2=width_col2)

1 Comment

It works Thanks. But I'm surprised there are no module to do this natively!
6

It seems like you want your columns left-justified, but I haven't seen any answers mention the ljust string method, so I'll demonstrate that in Python 2.7:

def bar(item):
    return item.replace('foo','bar')

width = 20
mylist = ['foo1','foo200000','foo33','foo444']

for item in mylist:
    print "{}| {}".format(item.ljust(width),bar(item).ljust(width))

foo1                | bar1
foo200000           | bar200000
foo33               | bar33
foo444              | bar444

For your reference, running help('abc'.ljust) gives you this:

S.ljust(width[, fillchar]) -> string

It looks like the ljust method takes your specified width and subtracts the length of the string from that, and pads the right side of your string with that many characters.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.