On Programming

A discussion of programming strategies and results

Simple ASCII Tables in Python

| Comments

I’ve written a very simple ASCII table printer for python.

print_table
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
  def print_table(lines, separate_head=True):
      """Prints a formatted table given a 2 dimensional array"""
      #Count the column width
      widths = []
      for line in lines:
          for i,size in enumerate([len(x) for x in line]):
              while i >= len(widths):
                  widths.append(0)
              if size > widths[i]:
                  widths[i] = size

      #Generate the format string to pad the columns
      print_string = ""
      for i,width in enumerate(widths):
          print_string += "{" + str(i) + ":" + str(width) + "} | "
      if (len(print_string) == 0):
          return
      print_string = print_string[:-3]

      #Print the actual data
      for i,line in enumerate(lines):
          print(print_string.format(*line))
          if (i == 0 and separate_head):
              print("-"*(sum(widths)+3*(len(widths)-1)))
To use this, pass a multidimensional array to print_table()
1
2
3
4
5
6
  rows = []
  rows.append(("Name", "Age", "Gender"))
  rows.append(("Fred", "2", "Male"))
  rows.append(("Amy", "90", "Female"))
  rows.append(("Iguanas Are Lame", "97", "Male"))
  print_table(rows)
Running this you will get the output
1
2
3
4
5
  Name             | Age | Gender
  -------------------------------
  Fred             | 2   | Male
  Amy              | 90  | Female
  Iguanas Are Lame | 97  | Male

Comments