Skip to content

Instantly share code, notes, and snippets.

@eirenik0
Created March 26, 2014 17:35
Show Gist options
  • Save eirenik0/9788876 to your computer and use it in GitHub Desktop.
Save eirenik0/9788876 to your computer and use it in GitHub Desktop.
print table in console
def printTable( data, header=None ):
lens = [0]*len(data[0])
for row in data:
for numCol, column in enumerate(row):
cLen = len(str(column))
if lens[numCol] < cLen:
lens[numCol] = cLen
res = ""
spacer = lambda lenList: '+' + '+'.join( '-'*(x+2) for x in lenList ) + '+'
drawRow = lambda lenList, valueList: '|' + "".join(
' %s ' % item + ' ' * (lenList[num] - len(str(item))) + '|'
for num, item in enumerate(valueList) )
if header:
for numCol, column in enumerate(header):
cLen = len(str(column))
if lens[numCol] < cLen:
lens[numCol] = cLen
res += spacer(lens)+ "\n"
res += drawRow( lens, header )+ "\n"
res+= spacer(lens) + "\n"
for r in data:
res += drawRow( lens, r )+ "\n"
res+= spacer(lens)+ "\n"
return res
@eirenik0
Copy link
Author

header: printTable([[1,2,3],[4,5,6]], ['col 1', 'col 2', 'col 3'])

+-------+-------+-------+
| col 1 | col 2 | col 3 |
+-------+-------+-------+
| 1 | 2 | 3 |
| 4 | 5 | 6 |
+-------+-------+-------+

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment