This is How You Color Print Out in Python

Julio Souto
Python in Plain English
3 min readMay 29, 2021

--

Many Python programmers depend on printing out statements on console, as a GUI isn’t always necessary. The issue sometimes is that a black and white console doesn’t help much when one has several console windows opened and running different functions. For example:

Honestly, you are not going to see what’s wrong (or right) easily when everything is just white on a black background.

So here it comes a library to help us out, fortunately! It’s called Termcolor. So let’s install it via python -m pip install termcolor command.

How to use it

It’s pretty simple. As simples as Python.

from termcolor import coloredprint(colored('Hello', 'red'), colored('Medium', 'yellow'), colored('world', 'green'))

Before and after

Regular printing vs Termcolor printing

Using try and except

from termcolor import coloredtry:
int('Hello World')
print(colored('Success!', 'green'))
except Exception as E:
print(colored(str(E), 'red'))
Printing an exception in red
from termcolor import coloredtry:
int('10')
print(colored('Success!', 'green'))
except Exception as E:
print(colored(str(E), 'red'))
Printing a success try in green

Printing an exception in color and bold

from termcolor import colored, cprint
import sys
try:
int('Hello World')
print(colored('Success!', 'green'))
except Exception as E:
cprint(str(E), 'red', attrs=['bold'], file=sys.stderr)
Printing an exception in red and bold

Printing try and exception in red and green backgrounds

from termcolor import colored, cprinttry:
int('Hello World')
print(colored('Success', 'green', attrs=['reverse', 'blink']))
except Exception as E:
print(colored(str(E), 'red', attrs=['reverse', 'blink']))
Printing an exception in red background
from termcolor import colored, cprinttry:
int('10')
print(colored('Success', 'green', attrs=['reverse', 'blink']))
except Exception as E:
print(colored(str(E), 'red', attrs=['reverse', 'blink']))
Printing a success try in green background

Conclusion

This library definitely helps us easily checking what’s going on in the code and on the console window without much effort, by just adapting the print statement a bit.

Have you ever used any of these? Please let me know in the comments. You can also follow me here, so you can track what’s next to come.

I hope you enjoyed this article.

More content at plainenglish.io

--

--

I am something between a Software Engineer and a Solutions Architect, leading the Innovation department for DSV Brazil.