1

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

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
rodude123
  • 294
  • 3
  • 19
  • 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 Answers2

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)) + " |")
Community
  • 1
  • 1
m0bi5
  • 8,900
  • 7
  • 33
  • 44