How to Print Colored Text in Python

Introduction

It's typical for CLI apps to return text in the same color of the terminal. There are always cases when we want to highlight output to the user, for example, a warning or error message. In those cases, a dash of color could make a difference.

This article shows you how to print colored output in the terminal in Python with and without libraries.

ANSI Escape Sequences

Your Teletypewriter (TTY), or rather your terminal, is not only capable of showing the output of a program. It can display a moving cursor, color the text, clear the entire screen, and much more than just static output. You may have seen command-line utilities with colorful text and progress bars. How do we control the presentation of the data we're are outputting to the terminal?

We use ANSI Escape Sequences/Codes. These are special strings that modify the behavior of the terminal. A familiar example would be the \n character, which is a New Line sequence. Entering this character will print a new line in the output.

The text is colored on your terminal based on ANSI Escape sequences. This article focuses on the escape sequences to color text.

Two color schemes are widely used in the terminals:

  • 16 colors (8 Background + 8 Foreground)
  • 256 colors

Let's begin coloring our output with the 16 color option.

16 Colors in Raw Python

The 16 colors scheme comprises two sets of 8 colors each (8 backgrounds and 8 foregrounds) and they can be displayed in the terminal by using the following syntax:

16 colors syntax

Let's put this to the test, by printing a cheesy color pattern with a red bold text and yellow background. The style code to represent bold text is 2. The color codes for the foreground red text is 31 and 43 for the yellow background. So, with that in mind, the syntax for representing this layout is:

print('\033[2;31;43m CHEESY')

Run the above command in your Python interpreter (or a file). You will see this output:

16 colors - example1

That's not quite right, our cheesy text is spilling over to the next line. We need a reset point to stop the printing of colors. This can be done by appending \033[0;0m to the string as:

print('\033[2;31;43m CHEESY \033[0;0m')

The \033[0;0m code represents a reset pattern that returns the terminal back to its original color scheme. This will provide the following output:

16 colors - example1

Looks much better.

16 Colors In Colorama - A Built-in Module

Colorama is a Python package that provides methods to print colored text in Python. It only supports the 16-colors scheme. The module prepares the ANSI Escape sequences to produce the colored text. Let's install the module with pip:

$ pip install colorama

We recommend you install it within a virtual environment. Once set up, let's get to printing colored text with Colorama:

# colorama_demo.py
from colorama import init, Fore, Back, Style

# Initializes Colorama
init(autoreset=True)

print(Style.BRIGHT + Back.YELLOW + Fore.RED + "CHEESY")

We first import the functions: init() (to initialize the module and to set the autoreset to True so we don't have to reset it manually), Fore (Foreground text object), Back (Background Object) and Style (Style Object). Each object has its own set of constants that can be called in the print() function.

By appending these components in a human-friendly way, Colorama converts values like YELLOW to 43, for the Back object, RED to 31 for the Fore object, etc. Under the hood, we end up with an ANSI Sequence, just like last time, though, we don't have to know the codes ourselves - Colorama does this for us.

No reset pattern is required, since we've set the autoreset argument to True while initializing the instance.

Running the code will display this:

Colorama - example

256 Colors in Raw Python

With the advancement in technologies, the 256-color scheme is the most commonly found in terminals. If you are on a Linux based OS, you can check your terminal-supported color scheme by entering the following command:

$ echo $TERM

If this command returns xterm-256color, then your terminal supports a maximum of 256 colors.

Wondering what those colors are?

We can dive in right after we understand the syntax of a 256-color scheme. Working with 256 colors is a bit different than working with the 16-color scheme:

256 colors - syntax

There's a placeholder to determine whether the color will be applied to the text or the background; 38;5; is for the text and 48;5; is for the background. This is followed by the color code ranging from 0 to 255.

Based on the above syntax, let's try recreating the StackAbuse logo in Python using an ANSI Escape Sequence.

The logo contains a pale grey background (\033[48;5;236m) with the words: Stack in white (\033[38;5;231m) and Abuse in orange (\033[38;5;208m). And of course, the reset code needs to be embedded in the string.

That being said, we can recreate the logo with this ANSI Sequence:

>>> print("\033[48;5;236m\033[38;5;231mStack \033[38;5;208mAbuse\033[0;0m")

This results in:

Stack Abuse Logo - in Color

Awesome! What other colors can the terminal print? Let's take a look, by printing all the 256 colors supported by the terminal:

# colorspep8.py
def colors_16(color_):
    return("\033[2;{num}m {num} \033[0;0m".format(num=str(color_)))


def colors_256(color_):
    num1 = str(color_)
    num2 = str(color_).ljust(3, ' ')
    if color_ % 16 == 0:
        return(f"\033[38;5;{num1}m {num2} \033[0;0m\n")
    else:
        return(f"\033[38;5;{num1}m {num2} \033[0;0m")

print("The 16 colors scheme is:")
print(' '.join([colors_16(x) for x in range(30, 38)]))
print("\nThe 256 colors scheme is:")
print(' '.join([colors_256(x) for x in range(256)]))

This script contains two functions that print the variable you pass into them, in the respective ANSI Escape Sequences. Once we run the script, and pass in x in a certain range, such as (30,38] for the 16-color scheme, or (0-255] for the 256-color scheme, it'll print out the indices in the colors at those values.

This will print out both color-coded schemes in the terminal:

Stack Abuse Logo - in Color

This can be very helpful as a quick reference while building command-line utilities.

Conclusion

In this tutorial, we've gone over how to print colored output, for the characters we send off to the stdout stream. We've explored how to do this using the built-in functionality Python offers, as well as how to use the Colorama library.

Author image
Chennai, India Twitter Website
Pythonist 🐍| Linux Geek who codes on WSL | Data & Cloud Fanatic | Blogging Advocate | Author