Fundamentals 11 min read

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

This tutorial explains how to use ANSI escape sequences, 16‑color and 256‑color schemes, and the Python Colorama library to display colored and styled text, background colors, and cursor effects in terminal windows, with complete code examples and usage notes.

Sohu Tech Products
Sohu Tech Products
Sohu Tech Products
How to Output Colored Text in the Terminal Using ANSI Escape Sequences and Python

In a terminal the default output is a single colour (black background with white text), which may not be suitable for highlighting warnings or prompts during rapid output.

This article introduces methods for printing coloured text to a terminal interface.

# 1. ANSI Escape Sequences

Terminals can do more than static output – they can move the cursor, colour text, clear the screen, display blinking cursors or progress bars, etc. The simplest example of changing terminal behaviour is inserting a newline with the escape string \n .

# 2. Colour Schemes

Two colour schemes are widely used in terminals:

16 colours (8 foreground + 8 background) – the foreground is the colour of the text itself.

255 colours.

16 Colours

The 16‑colour scheme consists of two groups of eight colours, one for the background and one for the foreground. The syntax is:

Example:

\033[1;32;40m

Here \033[ is the escape character, 1 means bold/high‑light, 32 sets the foreground colour to green, and 40 sets the background colour to black.

The resulting terminal output looks like this:

Escape characters

Escape characters can be expressed in three forms:

Hexadecimal: \x1b[

Unicode: \u001b[

Octal: \033[

Styles

Style codes control the visual appearance of the text:

0 (default), 1 (bold/highlight), 22 (normal intensity)

4 (underline), 24 (no underline), 5 (blink), 25 (no blink)

7 (inverse), 27 (no inverse)

print('\033[0;32;40m这是一行测试字体\033[0m')
print('\033[1;32;40m这是一行测试字体\033[0m')
print('\033[22;32;40m这是一行测试字体\033[0m')
print('\033[4;32;40m这是一行测试字体\033[0m')
print('\033[24;32;40m这是一行测试字体\033[0m')
print('\033[5;32;40m这是一行测试字体\033[0m')
print('\033[25;32;40m这是一行测试字体\033[0m')
print('\033[7;32;40m这是一行测试字体\033[0m')
print('\033[27;32;40m这是一行测试字体\033[0m')

Note that the actual visual effect depends on the terminal; CMD may not recognise the codes, while Windows Terminal does.

Colour Settings

Foreground colours : 30 (black), 31 (red), 32 (green), 33 (yellow), 34 (blue), 35 (magenta), 36 (cyan), 37 (white)

Background colours : 40 (black), 41 (red), 42 (green), 43 (yellow), 44 (blue), 45 (magenta), 46 (cyan), 47 (white)

Examples of foreground colour output:

print('\033[1;30;40m这是一行黑色测试字体\033[0m')
print('\033[1;31;40m这是一行红色测试字体\033[0m')
print('\033[1;32;40m这是一行绿色测试字体\033[0m')
print('\033[1;33;40m这是一行黄色测试字体\033[0m')
print('\033[1;34;40m这是一行蓝色测试字体\033[0m')
print('\033[1;35;40m这是一行洋红测试字体\033[0m')
print('\033[1;36;40m这是一行青色测试字体\033[0m')
print('\033[1;37;40m这是一行白色测试字体\033[0m')

Examples of background colour output:

print('\033[1;37;40m这是一行黑色测试背景\033[0m')
print('\033[1;37;41m这是一行红色测试背景\033[0m')
print('\033[1;37;42m这是一行绿色测试背景\033[0m')
print('\033[1;37;43m这是一行黄色测试背景\033[0m')
print('\033[1;37;44m这是一行蓝色测试背景\033[0m')
print('\033[1;37;45m这是一行洋红测试背景\033[0m')
print('\033[1;37;46m这是一行青色测试背景\033[0m')
print('\033[1;37;47m这是一行白色测试背景\033[0m')

Colorama – a Colour‑Output Module

Manually adding escape sequences for every print statement is cumbersome; the colorama library simplifies colour output.

from colorama import init, Fore, Back, Style

# Initialise Colorama
init(autoreset=True)

print(Style.BRIGHT + Back.YELLOW + Fore.RED + "Sample coloured text using Colorama")

Simple Colour Function

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):
    str = str_text
    style_code = style_dict[style]
    text_color_code = text_color_dict[text_color]
    back_color_code = background_color_dict[background_color]
    print_text = f'\033[{style_code};{text_color_code};{back_color_code}m{str}\033[0m'
    return print_text

256‑Colour Scheme

The 256‑colour output format differs slightly from the 16‑colour format.

The escape characters are the same as before (hex, Unicode, octal). To specify 256‑colour mode, use 38 for foreground or 48 for background followed by 5;{color_code} .

print("\033[48;5;160m\033[38;5;231m背景前景修改ABCDE \033[38;5;226m前景修改ABCDE\033[0;0m")

Example function to print all 256 foreground colours:

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('', end=' ')
print(''.join([print_colors_256(x) for x in range(256)]))

The actual appearance may vary depending on the terminal theme and its colour handling.

Author: HOLL4ND

Original link: https://www.kleinlam.space/…

pythonconsoleColoramaTerminalANSIcolorescape-sequence
Sohu Tech Products
Written by

Sohu Tech Products

A knowledge-sharing platform for Sohu's technology products. As a leading Chinese internet brand with media, video, search, and gaming services and over 700 million users, Sohu continuously drives tech innovation and practice. We’ll share practical insights and tech news here.

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.