Created
November 5, 2016 12:57
-
-
Save ekaitz-zarraga/662e72b78da336c331fbe2cc1879ff45 to your computer and use it in GitHub Desktop.
Easy and simple table printer for python
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
class Table: | |
""" | |
Simple terminal table printer: | |
| col1 | col2 | col3 | | |
-------+-------+-------+-------+ | |
row1 | 1 | 2 | 3 | | |
-------+-------+-------+-------+ | |
row2 | 4 | 5 | 6 | | |
-------+-------+-------+-------+ | |
""" | |
def __init__(self, rows, cols, data): | |
""" | |
Calculates sizes from the MAX length of all the cells, | |
not col by col. | |
You prefer that? Make changes and request a merge :D | |
""" | |
self.cols = cols | |
self.rows = rows | |
self.data = [] | |
# TODO Check if sizes match | |
all_fields = [] | |
all_fields += cols | |
all_fields += rows | |
for d in data: | |
strd = map( lambda x: str(x), d) | |
self.data.append(strd) | |
all_fields += strd | |
ws = map( lambda x: len(x), all_fields ) | |
self.width = max( ws ) + 2 | |
def __str__(self): | |
table = self.fill_field('') + '|' | |
for c in self.cols: | |
table += self.fill_field(c) + '|' | |
table += '\n' | |
table += self.hr() | |
for r, dr in zip(self.rows, self.data): | |
table += self.fill_field(r) + '|' | |
for d in dr: | |
table += self.fill_field(d) + '|' | |
table += '\n' | |
table += self.hr() | |
return table | |
def fill_field (self, field, char=' '): | |
result = char | |
for nchar in range(0,self.width): | |
if len(field) > len(result) -1 : | |
result += field[nchar] | |
else: | |
result += char | |
return result | |
def hr (self): | |
hr = '' | |
for col in range(len(self.cols)+1): | |
hr += self.fill_field('', '-') + '+' | |
return hr+'\n' | |
if __name__ == '__main__': | |
rows = ['row1','row2'] | |
cols = ['col1','col2','col3'] | |
data = [ | |
[ 1,2,3 ], | |
[ 4,5,6 ], | |
] | |
table = Table( rows, cols, data ) | |
print table | |
""" RESULT: | |
| col1 | col2 | col3 | | |
-------+-------+-------+-------+ | |
row1 | 1 | 2 | 3 | | |
-------+-------+-------+-------+ | |
row2 | 4 | 5 | 6 | | |
-------+-------+-------+-------+ | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment