24

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?

rahmu
  • 5,708
  • 9
  • 39
  • 57

6 Answers6

31

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)
Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
  • 3
    For others' reference, I had to change the format string to "{0:{1}}" to get it to work properly. – Darkhydro Aug 26 '14 at 22:03
  • Pylint complains about the * :(. It says "Used * or ** magic". – Pratik Khadloya Nov 07 '14 at 18:00
  • 6
    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))`. – PM 2Ring Nov 07 '15 at 18:24
  • 2
    Not really hard but certainly ugly and unnecessary. – Pithikos Jun 02 '17 at 08:16
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
Thomas Dignan
  • 7,052
  • 3
  • 40
  • 48
23

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
-----  ------  -------------
Rabinzel
  • 7,757
  • 3
  • 10
  • 30
TommasoF
  • 795
  • 5
  • 21
  • Yeah, I used this one, and very simple to have a table like structure in just few lines of code! – Rahul Aug 03 '16 at 07:00
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   |
+----------+------+--------+
Priyam Singh
  • 816
  • 2
  • 11
  • 10
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)
user880480
  • 316
  • 1
  • 3
7

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.

foundling
  • 1,695
  • 1
  • 16
  • 22