Print Colors of terminal in Python

In the terminal, if you want to make text appear in colored mode, there are numerous ways in Python programming to achieve it. Python offers several modules and built-in methods to add colors to terminal output.

Using the termcolor Module

The termcolor module provides ANSI color formatting for terminal output. It's one of the most popular libraries for adding colors to text.

Installation

First, install the termcolor module using pip ?

pip install termcolor

Basic Usage

Here's how to use termcolor to print colored text ?

import sys
from termcolor import colored, cprint

# Using colored() function
text1 = colored('Hello, Tutorialspoint!', 'blue', attrs=['reverse', 'blink'])
print(text1)

# Using cprint() function
cprint('Hello, Python!', 'blue', 'on_white')

# Creating a custom print function
print_red_on_blue = lambda x: cprint(x, 'red', 'on_blue')
print_red_on_blue('Hello, from Data Science!')
print_red_on_blue('Hello, Python!')

# Printing numbers in green
for i in range(10):
    cprint(i, 'green', end=' ')

# Printing to stderr with bold attribute
cprint("Attention!", 'blue', attrs=['bold'], file=sys.stderr)

Using ANSI Escape Sequences

You can also use ANSI escape codes directly without external modules ?

# ANSI color codes
class Colors:
    RED = '\033[91m'
    GREEN = '\033[92m'
    YELLOW = '\033[93m'
    BLUE = '\033[94m'
    MAGENTA = '\033[95m'
    CYAN = '\033[96m'
    WHITE = '\033[97m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'
    END = '\033[0m'  # Reset to default color

# Using the color codes
print(Colors.RED + "This is red text" + Colors.END)
print(Colors.GREEN + "This is green text" + Colors.END)
print(Colors.BOLD + Colors.BLUE + "This is bold blue text" + Colors.END)

Available Colors and Attributes

The termcolor module supports various colors and text attributes ?

Text Colors Background Colors Attributes
red, green, yellow, blue on_red, on_green, on_yellow bold, dark, underline
magenta, cyan, white, grey on_blue, on_magenta, on_cyan blink, reverse, concealed

Example with Multiple Colors

from termcolor import cprint

# Different color examples
colors = ['red', 'green', 'yellow', 'blue', 'magenta', 'cyan']
text = "Colorful Python Programming"

for color in colors:
    cprint(f"{color.capitalize()}: {text}", color)

Conclusion

Python provides multiple ways to add colors to terminal output. Use the termcolor module for easy color formatting, or ANSI escape codes for more control without dependencies.

Updated on: 2026-03-25T05:21:18+05:30

852 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements