Skip to main content

Tabulate and Colorama

Problem: I want to use tabulate to print a simple table in nicely formatted columns but I also want to use colour. No indications of how to use colour in the docs and not much comes up in search, although there was something about being able to use the ANSI colour codes.

Answer:

The answer was in the docs,specifically, this line gives you the answer, although it is not clear what the answer is in code terms.

"Printing small tables without hassle: just one function call, formatting is guided by the data itself"

In other words you format the underlying list, tabulate just prints whatever it gets.

Here is a little example.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
from colorama import init, deinit, Fore, Style
from tabulate import tabulate

#overide terminal colors
init()

#example list with colour formating from colorama module
list = [(Fore.RED+'a','b','c'),(Fore.GREEN+'1',Fore.WHITE+'2','3'+Fore.RED)]

#set colour for first bit of table
print (Fore.RED)

#simple tabulate list
print (tabulate(list))

#reset colours and finish overide
print(Style.RESET_ALL)
deinit()

Things to note:

  • once you set a cell the color stays until you change it
  • depending on the table style you may need to set a colour first and last after this list
Finally, in order to solve my problem, all I needed to do was take a list and iterate through adding the Fore colour to each cell to create a new list. Pass the new list to tabulate and my table was printed with all the colours I needed.

It took a while to solve this one, but I got there in the end.

Comments