Beginner

Introduction to Colored Terminal Output in Python

Have you ever noticed how modern command-line applications display colorful output? Success messages appear in green, warnings shine in yellow, and errors stand out in red. Whether you’re building CLI tools, debugging with colored logging output, or creating interactive terminal applications, adding color to your Python strings can dramatically improve user experience and make information easier to scan and understand.

The good news is that printing colored text in Python is surprisingly simple and doesn’t require complex external dependencies. Whether you prefer using built-in ANSI escape codes, lightweight libraries like colorama and termcolor, or powerful formatting tools like rich, Python offers multiple approaches to suit your needs. Even beginners can master colored text output in just a few minutes.

In this tutorial, we’ll explore four different methods to print colored strings in Python, from the most straightforward ANSI codes to advanced formatting options. By the end, you’ll understand how terminal colors work, how to choose the right approach for your project, and how to implement colored output in real-world applications like logging systems and status reporters.

Quick Example: Print Colored Text

Can’t wait to see colored text? Here’s the simplest way using ANSI escape codes:

# quick_color.py
print("\033[92mSuccess! Operation completed.\033[0m")
print("\033[93mWarning: Check this value.\033[0m")
print("\033[91mError: Something went wrong.\033[0m")

Output:

Success! Operation completed. [displayed in green]
Warning: Check this value. [displayed in yellow]
Error: Something went wrong. [displayed in red]

What are ANSI Escape Codes?

ANSI escape codes are special character sequences that tell your terminal to change text color and styling. They follow the pattern \033[CODEm where CODE represents a specific color or style. The sequence always ends with \033[0m to reset formatting back to normal.

Here’s a quick reference table of common ANSI color codes:

Color Foreground Code Background Code
Black 30 40
Red 31 41
Green 32 42
Yellow 33 43
Blue 34 44
Magenta 35 45
Cyan 36 46
White 37 47
Bright Green 92 102
Bright Yellow 93 103
Bright Red 91 101

ANSI codes also support text styling. Use 1 for bold, 2 for dim, 4 for underline. Combine multiple codes with semicolons: \033[1;92m creates bold bright green text.

Using ANSI Escape Codes Directly

The most minimal approach is to use ANSI codes directly in your strings. This works on macOS, Linux, and modern Windows 10+ systems. No installation required—just pure Python.

# ansi_colors.py
# Define reusable color constants
GREEN = "\033[92m"
YELLOW = "\033[93m"
RED = "\033[91m"
BLUE = "\033[94m"
RESET = "\033[0m"

# Use in print statements
print(f"{GREEN}Success!{RESET} Operation completed.")
print(f"{YELLOW}Warning:{RESET} Check this configuration.")
print(f"{RED}Error:{RESET} Connection failed.")
print(f"{BLUE}Info:{RESET} Processing 1000 items.")

# Bold and underline
BOLD_GREEN = "\033[1;92m"
UNDERLINE = "\033[4m"
print(f"{BOLD_GREEN}{UNDERLINE}Important Notice{RESET}")

# Background colors
BG_RED = "\033[41m"
WHITE = "\033[37m"
print(f"{BG_RED}{WHITE}CRITICAL{RESET} System failure detected.")

Output:

Success! Operation completed. [green text]
Warning: Check this configuration. [yellow warning]
Error: Connection failed. [red error]
Info: Processing 1000 items. [blue info]
Important Notice [bold green underlined]
CRITICAL System failure detected. [white text on red background]

Using the colorama Library (Cross-Platform)

While ANSI codes work great on most systems, Windows PowerShell can be finicky. The colorama library handles platform differences automatically and provides a cleaner API. Install it with pip install colorama.

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

# Initialize colorama (enables support on Windows)
init(autoreset=True)

print(f"{Fore.GREEN}Success!{Style.RESET_ALL} Your file was saved.")
print(f"{Fore.YELLOW}Warning:{Style.RESET_ALL} Disk space running low.")
print(f"{Fore.RED}Error:{Style.RESET_ALL} Database connection timeout.")

# Background colors
print(f"{Back.CYAN}{Fore.BLACK}Info{Style.RESET_ALL} Processing complete.")

# Text styling
print(f"{Style.BRIGHT}{Fore.BLUE}Important update available!{Style.RESET_ALL}")
print(f"{Style.DIM}{Fore.WHITE}Deprecated function{Style.RESET_ALL}")

# Combine multiple attributes
print(f"{Style.BRIGHT}{Fore.RED}{Back.YELLOW}ALERT{Style.RESET_ALL} Manual intervention required.")

Output:

Success! Your file was saved. [green]
Warning: Disk space running low. [yellow]
Error: Database connection timeout. [red]
Info Processing complete. [black text on cyan]
Important update available! [bright blue]
Deprecated function [dim white]
ALERT Manual intervention required. [bright red on yellow background]

Using the termcolor Library

For a lightweight alternative, termcolor offers a simple function-based API. Install with pip install termcolor. It’s ideal when you need quick colored output without extra features.

# termcolor_example.py
from termcolor import colored

# Simple colored text
print(colored("Success!", "green"), "Your changes were saved.")
print(colored("Warning:", "yellow"), "This feature is deprecated.")
print(colored("Error:", "red"), "Authentication failed.")
print(colored("Debug:", "cyan"), "Current value = 42")

# Add background colors
print(colored("CRITICAL", "white", "on_red"), "System overload detected.")
print(colored("INFO", "black", "on_green"), "Backup completed successfully.")

# Add text attributes (bold, dark, underline)
print(colored("Important", "blue", attrs=["bold"]))
print(colored("Deprecated", "white", attrs=["dark"]))
print(colored("Required", "red", attrs=["bold", "underline"]))

# Multiple attributes
print(colored("ALERT", "white", "on_yellow", attrs=["bold", "blink"]))

Output:

Success! Your changes were saved. [green]
Warning: This feature is deprecated. [yellow]
Error: Authentication failed. [red]
Debug: Current value = 42 [cyan]
CRITICAL System overload detected. [white on red]
INFO Backup completed successfully. [black on green]
Important [bold blue]
Deprecated [dark white]
Required [bold underlined red]
ALERT [bold yellow with blinking]

Using the rich Library for Advanced Formatting

The rich library is a powerhouse for terminal formatting, supporting colors, tables, panels, progress bars, and syntax highlighting. Install with pip install rich. Use it when you need professional-looking terminal output.

# rich_example.py
from rich.console import Console
from rich import print as rprint
from rich.panel import Panel
from rich.table import Table

console = Console()

# Simple colored text
console.print("[green]Success![/green] Operation completed.")
console.print("[yellow]Warning:[/yellow] Check system resources.")
console.print("[red]Error:[/red] Network timeout occurred.")

# Using rprint function (shorthand)
rprint("[bold blue]Important notice[/bold blue]")
rprint("[dim italic cyan]System info[/dim italic cyan]")

# Panels for highlighted messages
console.print(Panel("[green bold]✓ Deployment Successful[/green bold]", expand=False))
console.print(Panel("[yellow bold]⚠ Review Required[/yellow bold]", expand=False))
console.print(Panel("[red bold]✗ Critical Error[/red bold]", expand=False))

# Tables with colors
table = Table(title="System Status", show_header=True, header_style="bold magenta")
table.add_column("Component", style="cyan")
table.add_column("Status", style="green")
table.add_row("Database", "[green]Online[/green]")
table.add_row("Cache", "[yellow]Warming[/yellow]")
table.add_row("API", "[red]Offline[/red]")
console.print(table)

Output:

Success! Operation completed. [green]
Warning: Check system resources. [yellow]
Error: Network timeout occurred. [red]
Important notice [bold blue]
System info [dim italic cyan]
┌─ Deployment Successful ─┐ [green box]
⚠ Review Required [yellow box]
✗ Critical Error [red box]
[System Status table with colored columns]

Adding Color to Logging Output

Colored output becomes especially valuable in logging systems where different severity levels are immediately recognizable. Here’s how to add colors to Python’s logging module:

# colored_logging.py
import logging
from colorama import Fore, Style, init

init()

class ColoredFormatter(logging.Formatter):
    COLORS = {
        "DEBUG": Fore.CYAN,
        "INFO": Fore.GREEN,
        "WARNING": Fore.YELLOW,
        "ERROR": Fore.RED,
        "CRITICAL": f"{Fore.RED}{Style.BRIGHT}"
    }

    def format(self, record):
        log_color = self.COLORS.get(record.levelname, Fore.WHITE)
        record.levelname = f"{log_color}{record.levelname}{Style.RESET_ALL}"
        return super().format(record)

# Configure logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

handler = logging.StreamHandler()
handler.setFormatter(ColoredFormatter(
    "%(levelname)s - %(name)s - %(message)s"
))
logger.addHandler(handler)

# Use the logger
logger.debug("Debugging information retrieved")
logger.info("Application started successfully")
logger.warning("Low memory condition detected")
logger.error("Failed to connect to database")
logger.critical("System shutdown initiated")

Output:

DEBUG - __main__ - Debugging information retrieved [cyan]
INFO - __main__ - Application started successfully [green]
WARNING - __main__ - Low memory condition detected [yellow]
ERROR - __main__ - Failed to connect to database [red]
CRITICAL - __main__ - System shutdown initiated [bright red]

Real-Life Example: Colored CLI Status Reporter

Let’s build a practical application that monitors system status and displays results with color-coded output. This demonstrates how colors improve information clarity in real scenarios.

# system_status.py
import psutil
from colorama import Fore, Style, init

init(autoreset=True)

def get_status_color(value, thresholds):
    """Determine color based on value thresholds."""
    if value < thresholds["warning"]:
        return Fore.GREEN, "OK"
    elif value < thresholds["critical"]:
        return Fore.YELLOW, "WARNING"
    else:
        return Fore.RED, "CRITICAL"

def report_system_status():
    """Display colored system status report."""
    print(f"{Style.BRIGHT}=== System Status Report ==={Style.RESET_ALL}\n")

    # CPU Usage
    cpu_percent = psutil.cpu_percent(interval=1)
    color, status = get_status_color(cpu_percent,
                                     {"warning": 50, "critical": 80})
    print(f"CPU Usage:    {color}{cpu_percent:>6.1f}%{Style.RESET_ALL} [{status}]")

    # Memory Usage
    mem = psutil.virtual_memory()
    color, status = get_status_color(mem.percent,
                                     {"warning": 70, "critical": 90})
    print(f"Memory:       {color}{mem.percent:>6.1f}%{Style.RESET_ALL} [{status}]")

    # Disk Usage
    disk = psutil.disk_usage("/")
    color, status = get_status_color(disk.percent,
                                     {"warning": 75, "critical": 90})
    print(f"Disk Usage:   {color}{disk.percent:>6.1f}%{Style.RESET_ALL} [{status}]")

    # Process Count
    process_count = len(psutil.pids())
    color = Fore.GREEN if process_count < 200 else Fore.YELLOW
    print(f"Processes:    {color}{process_count:>6}{Style.RESET_ALL}")

    print(f"\n{Fore.CYAN}Generated at {Style.BRIGHT}{get_timestamp()}{Style.RESET_ALL}")

def get_timestamp():
    """Return current timestamp."""
    from datetime import datetime
    return datetime.now().strftime("%Y-%m-%d %H:%M:%S")

if __name__ == "__main__":
    report_system_status()

Output:

=== System Status Report ===

CPU Usage:     45.2% [OK] [green]
Memory:        68.3% [OK] [green]
Disk Usage:    82.1% [WARNING] [yellow]
Processes:       187 [green]

Generated at 2026-03-18 14:32:15 [cyan]

Frequently Asked Questions

Q1: Why don’t colors work on my Windows system?

By default, older Windows versions don’t support ANSI codes. Solution: Use the colorama library which automatically enables support on Windows, or enable ANSI in Windows 10+ through system settings. The init() function in colorama handles this automatically.

Q2: Can I use colored text in files instead of just the console?

ANSI codes appear as raw escape sequences in text files. If you want colors in saved files, use HTML or Markdown instead. For console output only, ANSI codes work perfectly. When writing to log files, consider stripping codes with libraries like colorama.deinit() or use separate formatting for file vs. console output.

Q3: Which library should I choose for my project?

Choose based on your needs: Use raw ANSI codes for minimal dependencies; use colorama for reliable cross-platform support; use termcolor for simple, lightweight colored text; use rich for advanced formatting, tables, and panels. For most projects, colorama offers the best balance.

Q4: How do I create custom colors beyond the basic set?

Standard ANSI codes provide 8 basic colors plus 8 bright variants. For 256-color support, use escape codes like \033[38;5;196m (where 196 is a color index). For true color (16 million colors), use RGB format: \033[38;2;255;0;0m for red. The rich library handles 256-color and true color automatically.

Q5: Are ANSI colors supported in Jupyter notebooks?

Most Jupyter implementations don’t render terminal ANSI colors. However, the rich library integrates beautifully with Jupyter and automatically detects the environment to output proper HTML formatting. For Jupyter notebooks, rich is your best choice.

Q6: What about accessibility? Are colored outputs accessible?

Never rely on color alone to convey information. Always combine color with text labels, symbols, or other indicators. For example, use both color and text: “[ERROR]” in red rather than just red text. This ensures visually impaired users can understand your application.

Conclusion

Printing colored strings in Python is simple, powerful, and available through multiple approaches. Whether you choose raw ANSI codes for minimal overhead, colorama for cross-platform reliability, termcolor for lightweight simplicity, or rich for professional formatting, you now have the knowledge to add vibrant output to your applications.

Colored output transforms CLI applications from bland text dumps into clear, scannable interfaces. Your logging becomes easier to understand, your error messages stand out, and your users appreciate the improved clarity. Start with the approach that fits your project, and remember: colors enhance understanding—never use them as the only way to communicate critical information.

Ready to explore more? Check out the official documentation for colorama and rich to discover even more advanced features and capabilities.