Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python format tabular output [duplicate]

Tags:

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?

like image 686
rahmu Avatar asked Dec 02 '11 12:12

rahmu


People also ask

How do you show data in tabular format in Python?

Use Tabulate The first argument of the Tabulate function can transform all the below data types into a table: list of lists or another iterable of iterables. list or another iterable of dicts (keys as columns) dict of iterables (keys as columns)

Do you use data when tabular formatting?

Answer. HTML table tag is used to display data in tabular form (row * column).


1 Answers

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) 
like image 198
Sven Marnach Avatar answered Oct 09 '22 09:10

Sven Marnach