How to Print Colored Text in Python with ANSI Codes
Define a small Colors class and a colored() helper to print styled terminal text using ANSI escape codes.
Python code
25 linesclass Colors:
RESET = "\033[0m"
RED = "\033[31m"
GREEN = "\033[32m"
YELLOW = "\033[33m"
BLUE = "\033[34m"
MAGENTA = "\033[35m"
CYAN = "\033[36m"
WHITE = "\033[37m"
BOLD = "\033[1m"
UNDERLINE = "\033[4m"
def colored(text, color):
return f"{color}{text}{Colors.RESET}"
if __name__ == "__main__":
print(colored("Red text", Colors.RED))
print(colored("Green text", Colors.GREEN))
print(colored("Yellow text", Colors.YELLOW))
print(colored("Blue text", Colors.BLUE))
print(colored("Magenta text", Colors.MAGENTA))
print(colored("Cyan text", Colors.CYAN))
print(colored(f"{Colors.BOLD}Bold and underlined{Colors.UNDERLINE}", Colors.WHITE))
Output
Red text
Green text
Yellow text
Blue text
Magenta text
Cyan text
Bold and underlined
How it works
ANSI escape codes are interpreted by most modern terminals to change text color and style. The \033[ prefix starts an escape sequence, the number (like 31 for red) selects the attribute, and m ends it. The colored() function wraps your text with the chosen color code and appends Colors.RESET so styling doesn't bleed into subsequent output. Combining codes like BOLD and UNDERLINE before the text applies multiple styles at once, which you can see in the last print call. This works without any third-party dependencies, keeping your script lightweight and portable.
Common mistakes
- Forgetting to reset codes, causing all following output to stay colored
- Using `\e` instead of `\033` which breaks on some platforms
- Applying color codes after the text instead of before it
Variations
- Use the `colorama` package to handle Windows terminals that don't support ANSI natively
- Define individual functions like `red(text)` instead of a helper taking a color parameter
Real-world use cases
- Highlighting success and error messages in a build or deployment script for faster visual scanning.
- Differentiating log levels (INFO, WARN, ERROR) in a CLI tool that prints structured output.
- Making verbose debug output visually distinct in a development tool that runs headless tests.
Sponsored
More from Functions & basics
- Add Type Hints to Function Parameters and Return in Python easy
- Benchmark list append vs comprehension in Python easy
- Build a Context Manager in Python with contextlib.contextmanager easy
- Build a Progress Callback Function for Loops in Python easy
- Cache expensive function with lru_cache in Python easy
- Calculate Time Difference Across Time Zones in Python easy
Keep learning
Related tutorials and quizzes for this topic.