Python format tabular output

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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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)

Method 2

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

Method 3

For more beautiful table use the tabulate module:

Tabulate link

Here reported an example:

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

Method 4

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

Method 5

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)

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x