How to print colored text in terminal in Python?

The most common way to print colored text in terminal is by printing ANSI escape sequences. However, this depends on the platform you are using. The easiest way is using colorama library. It lets you print colored terminal text on all platforms.

Install colorama #

pip install colorama

colorama is also available on conda

conda install -c anaconda colorama

Usage #

Initialize Colorama using:

from colorama import init
init()

You are now can use Colorama to print the colored text on terminal


from colorama import Fore, Back, Style
print(Fore.RED + 'This text is red')
print(Back.GREEN + 'and this is green backgroun')
print(Style.DIM + 'but this is dim text')
print(Style.RESET_ALL)
print('back to normal now')

or simply by manually printing ANSI sequences from your own code:

print('\033[31m' + 'some red text')
print('\033[39m') # and reset to default color

Using this way, you have to know the ANSI sequences. The former way which uses the constants is much easier.

Available formatting constants are:

Fore: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, RESET.
Back: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, RESET.
Style: DIM, NORMAL, BRIGHT, RESET_ALL

Colorama can also be used in conjunction with existing ANSI libraries such as Termcolor:

from colorama import init
from termcolor import colored

# use Colorama to make Termcolor work on Windows too
init()

# then use Termcolor for all colored text output
print(colored('Welcome to colored text terminal world!', 'green', 'on_red'))

Style.RESET_ALL resets foreground, background, and brightness. Colorama will perform this reset automatically on program exit

To stop using colorama before your program exits, simply call deinit(). This will restore stdout and stderr to their original values, so that Colorama is disabled. To resume using Colorama again, call reinit(); it is cheaper to calling init() again (but does the same thing).

Tags:

Python