How do I make a table in python. I am doing this at school where I am not allowed any extra addons such as tabulate or texttable and pretty table so could you guide me on how to do this thank you it is for python 3.4 or python 3.5
Asked
Active
Viewed 1,468 times
1
-
Possible duplicate of [Python format tabular output](http://stackoverflow.com/questions/8356501/python-format-tabular-output) – PM 2Ring Nov 07 '15 at 18:17
2 Answers
1
This is based on @SOReadytoHelp's solution. I updated it to Python 3 and included an example.
def print_table(table):
col_width = [max(len(str(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 = [['/', 2, 3],
['a', '2a', '3a'],
['b', '2b', '3b']]
print_table(table)
which prints
| / | 2 | 3 |
| a | 2a | 3a |
| b | 2b | 3b |

Joschua
- 5,816
- 5
- 33
- 44
-
FWIW, SO ReadytoHelp's code actually comes from accepted answer in his link, which was written by [Sven Marnach](http://stackoverflow.com/a/8356620/4014959). But your code is better than Sven's. :) – PM 2Ring Nov 07 '15 at 18:28
0
I should put this as a comment but as I dont have enough reputation I am posting this as an answer. Check this
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)) + " |")
-
-
-
-
Joschua's version with `max(len(str(x))` is a little more robust, since it can deal with a table of any type of object, but yours won't work properly with non-strings. But that may be ok for the OP's requirements. – PM 2Ring Nov 07 '15 at 18:14