Colored text output in Python (also in jupyter notebooks)

This post is a slight deviation from the usual Data Science learning path, but I think that there may be something useful also for those wanting to include a bit of interaction in their Jupyter Notebooks.

I have started teaching some python to my 14 years old son (on his request), and I decided to start by following some material freely available online, unfortunately for you readers, these references are in French. For those interested, these are the links, the material is really well done, and I am sure that there are equivalent English resources:

  • Python 3 Objective Jeux. This is a great resource, which is targeted to kids around the age of my son, where all chapters are based on building up simple games in python.
  • And this is a free text book, which can be used as a reference for the above

We started using Python notebook as our playground, and we have set for pyCharm Community Edition for when standalone programs will be needed. We also decided to settle for Python 3, and more precisely Python 3.6, as there is no point for legacy 2.7 when you start from scratch. During our Python teaching/learning sessions, I sometimes find useful (and joyful besides funny) to add a little bit of color in the text output. There is a very little and simple Python module that allows to do so: This is termcolor, which exposes two functions:

  • colored()
  • cprint()

Both of these have a use. Colored adds color tokens to a string and allows this string to be printed or used in any other way, compatible with the basic terminal output, see the following examples, always in Jupyter notebook for colored:

The options of colored() are many, and you do not need to specify the parameter names, save for the font attribute list, “attr”.

In the source code of the module, under the function __main__ there are several examples of this. Beware that in Jupyter notebook, the blink attribute does not work, as well as the concealed (if I have understood what it means).

The cprint function has been added to the module at a later stage and simply combines the functionalities of colored() and print().

Finally an example, a simple clock running in a jupyter cell, (but you can imagine stock tickers or any other output where an highlight is needed).

Note: This contains a trick to make the printouts always overwrite each other and appear in the same place (sys.stdout.write() and sys.stdout.flush() rather than print()). So there will be only one line printed over and over, and it shall look like this: