Created
May 12, 2016 09:08
-
-
Save fnkr/2580c43deb697aecb9e345ad305fca38 to your computer and use it in GitHub Desktop.
ASCII Tables with Python 3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Python 3 | |
def pprinttable(rows): | |
if len(rows) > 1: | |
headers = rows[0]._fields | |
lens = [] | |
for i in range(len(rows[0])): | |
lens.append(len(max([x[i] for x in rows] + [headers[i]],key=lambda x:len(str(x))))) | |
formats = [] | |
hformats = [] | |
for i in range(len(rows[0])): | |
if isinstance(rows[0][i], int): | |
formats.append("%%%dd" % lens[i]) | |
else: | |
formats.append("%%-%ds" % lens[i]) | |
hformats.append("%%-%ds" % lens[i]) | |
pattern = " | ".join(formats) | |
hpattern = " | ".join(hformats) | |
separator = "-+-".join(['-' * n for n in lens]) | |
print(hpattern % tuple(headers)) | |
print(separator) | |
for line in rows: | |
print(pattern % tuple(line)) | |
elif len(rows) == 1: | |
row = rows[0] | |
hwidth = len(max(row._fields,key=lambda x: len(x))) | |
for i in range(len(row)): | |
print("%*s = %s" % (hwidth,row._fields[i],row[i])) | |
from collections import namedtuple | |
Row = namedtuple('Row',['first','second','third']) | |
data = Row(1,2,3) | |
pprinttable([data, data]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment