Programming
python python-3.4 python-3.5
Updated Fri, 26 Aug 2022 09:26:30 GMT

How do I put things in a table in python


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




Solution

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 |




Comments (1)

  • +0 – FWIW, SO ReadytoHelp's code actually comes from accepted answer in his link, which was written by Sven Marnach. But your code is better than Sven's. :) — Nov 07, 2015 at 18:28