How do I print colored text to the terminal?
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
In Python, you can print colored text to the terminal using several methods. Here are the most popular approaches:
1. Using ANSI Escape Codes
ANSI escape codes are special sequences used to control text formatting, including color, boldness, and background.
Syntax:
\033[: Escape sequence to start.m: Ends the color/style formatting.0resets the style after the colored text.
Example:
Common Codes:
- Text Colors:
30: Black,31: Red,32: Green,33: Yellow34: Blue,35: Magenta,36: Cyan,37: White
- Styles:
0: Reset,1: Bold,4: Underline,7: Inverted colors
- Background Colors:
40: Black,41: Red,42: Green,43: Yellow44: Blue,45: Magenta,46: Cyan,47: White
2. Using the colorama Library (Cross-Platform)
colorama is a library that makes it easy to print colored text in a cross-platform way, especially on Windows where ANSI codes are not natively supported.
Installation:
Example:
Output:
Foresets text color.Backsets background color.Styleadds effects like bold (e.g.,Style.BRIGHT).
3. Using the termcolor Library
termcolor simplifies adding colors to terminal text.
Installation:
Example:
Output:
colored(text, color, on_color, attrs)formats the text.- Supported colors:
'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white'.
4. Using the rich Library (Advanced Features)
rich is a powerful library for rich text formatting, including color, bold, tables, and progress bars.
Installation:
Example:
Output:
rich uses a markup syntax similar to HTML for text formatting.
Summary Table
| Method | Library Required | Pros | Example |
| ANSI Codes | None | Simple, no extra library needed | \033[31mRed\033[0m |
| colorama | Yes | Cross-platform, easy to use | Fore.RED + "Text" |
| termcolor | Yes | Lightweight, clean API | colored("Text", "red") |
| rich | Yes | Advanced features (tables, markup) | console.print("[red]Text") |
Recommendation:
- Use
coloramafor basic, cross-platform terminal colors. - Use
richfor advanced text formatting and terminal enhancements. - Use ANSI escape codes for quick, lightweight color changes without libraries. 🚀
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.