Printing colored text in Python can be done using ANSI escape codes, libraries like Colorama or termcolor, or advanced tools like Rich. Below is a detailed guide with examples for each method:
1. ANSI Escape Codes (Manual Method)
ANSI codes are universal for most terminals (Linux/macOS/Windows 10+). They use escape sequences to style text.
Syntax
\033[<STYLE>;<COLOR>;<BACKGROUND>mTEXT\033[0m
\033[
: Start of the escape sequence.<STYLE>
: Text style (e.g., bold, underline).<COLOR>
: Text color (30-37, 90-97).<BACKGROUND>
: Background color (40-47, 100-107).m
: End of the escape sequence.\033[0m
: Reset all styles.
Color Codes
Type | Codes | Examples |
---|---|---|
Text | 30-37, 90-97 | 31 = Red |
Background | 40-47, 100-107 | 42 = Green |
Styles | 0 (reset), 1 (bold), 4 (underline), 7 (invert) |
Examples
# Red text
print("\033[31mThis is red text\033[0m")
# Bold yellow text
print("\033[1;33mBold yellow text\033[0m")
# Blue text on a white background
print("\033[34;107mBlue on white\033[0m")
# Underlined bright cyan (90-97 for bright colors)
print("\033[4;96mUnderlined bright cyan\033[0m")
# Combine styles: bold + underline + magenta text + cyan background
print("\033[1;4;35;46mBold, underlined magenta on cyan\033[0m")
2. Colorama (Cross-Platform Solution)
Colorama simplifies ANSI codes and ensures compatibility with Windows.
Installation
pip install colorama
Usage
from colorama import Fore, Back, Style, init
# Initialize for Windows (automatically strips ANSI on non-supported terminals)
init(autoreset=True) # Auto-reset styles after each print
print(Fore.RED + "Red text")
print(Back.GREEN + "Green background")
print(Fore.YELLOW + Back.BLUE + "Yellow on blue")
print(Style.BRIGHT + Fore.CYAN + "Bright cyan text")
print(Style.DIM + "Dim text") # Less common style
Key Features:
autoreset=True
: Automatically reset styles after each print.Fore
: Text colors (e.g.,Fore.RED
).Back
: Background colors (e.g.,Back.GREEN
).Style
: Text styles (e.g.,Style.BRIGHT
).
3. termcolor (Simpler Syntax)
The termcolor
library provides a user-friendly API.
Installation
pip install termcolor
Usage
from termcolor import colored, cprint
# Basic colored text
print(colored("Hello World!", "red"))
# Text with background and attributes
print(colored("Warning!", "yellow", "on_red", ["bold", "underline"]))
# Direct print using cprint
cprint("This is cyan", "cyan")
cprint("Bold magenta underline", "magenta", attrs=["bold", "underline"])
# List all supported colors and attributes
print(termcolor.COLORS) # Shows all text colors
print(termcolor.HIGHLIGHTS) # Shows all background colors
print(termcolor.ATTRIBUTES) # Shows all styles (bold, underline, etc.)
Supported Options
- Colors:
grey
,red
,green
,yellow
,blue
,magenta
,cyan
,white
. - Backgrounds: Prefix
on_
(e.g.,on_blue
). - Attributes:
bold
,dark
,underline
,blink
,reverse
,concealed
.
4. Advanced: Rich Library
For complex terminal styling (tables, progress bars, etc.), use Rich.
Installation
pip install rich
Usage
from rich.console import Console
console = Console()
# Basic colored text
console.print("This is [bold red]bold red[/] text")
# Combine styles
console.print("This is [underline green on yellow]styled text[/]")
# RGB/Hex colors (if terminal supports it)
console.print("[#FF00FF]Magenta text[/]")
console.print("[rgb(255,165,0)]Orange text[/]")
5. Practical Examples
Error/Warning Messages
# Using ANSI codes
print("\033[1;31m[ERROR]\033[0m File not found!")
# Using termcolor
from termcolor import colored
print(colored("[WARNING]", "yellow", attrs=["bold"]) + " Low disk space")
# Using Colorama
from colorama import Fore, Style
print(f"{Fore.RED}{Style.BRIGHT}[CRITICAL]{Style.RESET_ALL} System overheating")
Colorize Logs
import logging
from colorama import Fore, Style
logging.basicConfig(
format=f"{Fore.GREEN}%(asctime)s{Style.RESET_ALL} {Fore.BLUE}%(levelname)s{Style.RESET_ALL}: %(message)s",
level=logging.INFO
)
logging.info("This is an info message")
logging.warning("This is a warning message")
Notes
- Windows Compatibility: Use
colorama.init()
for ANSI support on older Windows versions. - Terminal Support: Not all terminals support ANSI codes (e.g., basic Windows Command Prompt).
- Reset Styles: Always reset styles with
\033[0m
orStyle.RESET_ALL
to avoid unintended formatting.
Choose the method that fits your use case:
- Quick Scripts: ANSI codes or
termcolor
. - Cross-Platform Apps:
Colorama
. - Complex UIs:
Rich
.