table formatter 02-17-2016, 06:58 AM
#1
This is a smaller part of the overall project (which should function similar to the pandas module when I'm done with it), but it's useful nonetheless. Look out for the full project on github and PyPI soonish.
Note: it's imported as a module, thus the __init__.py file
Other note: VERY alpha build right now, so expect bugs
__init__.py
formatting.py
Note: it's imported as a module, thus the __init__.py file
Other note: VERY alpha build right now, so expect bugs
Spoiler: Example
source:
output:
Code:
from <whatever you called the directory> import Table
t=Table(padding=(1,2),rows=(['foo','bar',123],['test',123,'test'],['a','b','c']),dividers=('-','|'))
print toutput:
Code:
foo | bar | 123
----------------------
test | 123 | test
----------------------
a | b | c
----------------------__init__.py
Code:
from formatting import TableFormatter
class Table(TableFormatter):
def __init__(self,**items):
for k,v in {'padding': (0,0),'rows': None,'dividers': False}.iteritems():
setattr(self,k,items.get(k,v))
if self.dividers:
self.dividers=tuple(self.dividers)
if len(self.dividers)>3:
raise ValueError('Too many values supplied for dividers (maximum 3)')
elif len(self.dividers)==2:
self.dividers=(self.dividers[0],self.dividers[1],self.dividers[0])
elif len(self.dividers)==1:
self.dividers=(self.dividers[0])*3
if type(self.padding)!=tuple:
self.padding=tuple(self.padding)
if len(self.padding)>2:
raise ValueError('Too many values supplied for padding (maximum 2)')
elif len(self.padding)==1:
self.padding=(self.padding[0],0)formatting.py
Code:
class TableFormatter:
def __str__(self):
_tmp,_ret=[],[]
_spacing=[max(map(len,map(str,i))) for i in zip(*[tuple(e) for e in self.rows])]
for r in self.rows:
for i in range(len(r)-1):
_tmp.append([str(x).ljust(_spacing[i]) for x in r])
for i in range(0,len(_tmp)-1,2):
if self.dividers:
row=(self.dividers[1]+' '*self.padding[0]).join([e+' '*self.padding[1] for e in _tmp[i]])
_ret.append(row)
_ret.append(self.dividers[0]*len(row))
else:
_ret.append(''.join([e+' '*self.padding[1] for e in _tmp[i]]))
return '\n'.join(_ret)It's often the outcasts, the iconoclasts ... those who have the least to lose because they
don't have much in the first place, who feel the new currents and ride them the farthest.
don't have much in the first place, who feel the new currents and ride them the farthest.















![[+]](https://sinister.ly/images/modern/collapse_collapsed.png)