Fundamentals 9 min read

How to Output Colored Text in the Terminal Using ANSI Escape Sequences and Colorama in Python

This tutorial explains how to use ANSI escape sequences and the Colorama library to print colored and styled text in a terminal, covering 16‑color and 256‑color schemes, style codes, and reusable Python functions for flexible CLI output.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
How to Output Colored Text in the Terminal Using ANSI Escape Sequences and Colorama in Python

By default a terminal shows output in a single color (white on black), which can be insufficient for highlighting warnings or prompts during rapid output. This article demonstrates how to print colored and styled text in a terminal using ANSI escape sequences and the Python Colorama library.

1. ANSI Escape Sequences

Terminals can move the cursor, clear the screen, and apply text colors or effects by printing special control strings. The simplest example is the newline character \n .

2. Color Schemes

Two color schemes are widely used:

16‑color (8 foreground + 8 background)

256‑color

16‑color

The 16‑color scheme uses two groups of eight codes: one for foreground (text) and one for background. Example escape string:

<code>\033[1;32;40m</code>

Here \033[ starts the escape, 1 sets bold/high‑intensity, 32 selects green foreground, and 40 selects black background. The resulting output appears as green text on a black background.

Escape characters can be expressed in three forms:

Hexadecimal: \x1b[

Unicode: \u001b[

Octal: \033[

Style codes control the text appearance:

0 – default

1 – bold/high‑intensity

4 – underline

5 – blink

7 – reverse video

<code>print('\033[0;32;40mThis is a test line\033[0m')
print('\033[1;32;40mThis is a test line\033[0m')
print('\033[22;32;40mThis is a test line\033[0m')
print('\033[4;32;40mThis is a test line\033[0m')
print('\033[24;32;40mThis is a test line\033[0m')
print('\033[5;32;40mThis is a test line\033[0m')
print('\033[25;32;40mThis is a test line\033[0m')
print('\033[7;32;40mThis is a test line\033[0m')
print('\033[27;32;40mThis is a test line\033[0m')
</code>

Foreground color codes (30‑37) and background color codes (40‑47) are listed below:

<code># Foreground colors
30: black, 31: red, 32: green, 33: yellow, 34: blue, 35: magenta, 36: cyan, 37: white
# Background colors
40: black, 41: red, 42: green, 43: yellow, 44: blue, 45: magenta, 46: cyan, 47: white
</code>

256‑color

The 256‑color mode uses 38 (foreground) or 48 (background) followed by ;5; and the color index (0‑255). Example:

<code>print("\033[48;5;160m\033[38;5;231mBackground and foreground test\033[0m")
</code>

A helper function can print all 256 colors:

<code>def print_colors_256(color_code):
    num1 = str(color_code)
    num2 = str(color_code).ljust(3, ' ')
    if color_code % 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("256 color scheme:")
print(' '.join([print_colors_256(x) for x in range(256)]))
</code>

Using Colorama

Manually adding escape codes for every print statement is cumbersome. The colorama module simplifies this by providing constants for styles, foreground, and background colors.

<code>from colorama import init, Fore, Back, Style

init(autoreset=True)
print(Style.BRIGHT + Back.YELLOW + Fore.RED + "Sample colored text")
</code>

Simple Color Function

A reusable function can build an escape string from dictionaries of style, text color, and background color:

<code>background_color_dict = {
    'BLACK':40, 'RED':41, 'GREEN':42, 'YELLOW':43,
    'BLUE':44, 'MAGENTA':45, 'CYAN':46, 'WHITE':47
}
text_color_dict = {
    'BLACK':30, 'RED':31, 'GREEN':32, 'YELLOW':33,
    'BLUE':34, 'MAGENTA':35, 'CYAN':36, 'WHITE':37
}
style_dict = {
    'normal':0, 'bold':1, 'light':2, 'italicize':3,
    'underline':4, 'blink':5
}

def set_text_color(str_text, style, text_color, background_color):
    style_code = style_dict[style]
    text_color_code = text_color_dict[text_color]
    back_color_code = background_color_dict[background_color]
    return f'\033[{style_code};{text_color_code};{back_color_code}m{str_text}\033[0m'
</code>

These techniques allow developers to create more readable and informative command‑line interfaces.

CLIPythonColoramaTerminalANSIText coloring
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.