Question
How can I output colored text to the terminal in Python?
I want to display text in different colors when printing to the command line or terminal from a Python program. What is the standard way to do this, and what should I be aware of when using it across environments?
Short Answer
By the end of this page, you will understand how Python can print colored terminal text using ANSI escape codes, when that approach works well, and what practical alternatives developers use in real projects. You will also see examples, common mistakes, and a small project that turns plain terminal output into clearer, color-coded messages.
Concept
Terminal color output in Python is usually done by printing ANSI escape codes along with your text.
An ANSI escape code is a special sequence of characters that tells the terminal to change how text should be displayed, such as:
- changing the text color
- changing the background color
- making text bold or underlined
- resetting the style back to normal
Python itself does not have a special print_color() function built into the standard print() function. Instead, you usually do one of these:
- print raw ANSI escape codes directly
- use a helper library such as
colorama - use a richer terminal formatting library such as
rich
A basic ANSI color sequence looks like this:
"\033[31mHello\033[0m"
Here:
\033[starts the escape sequence31mmeans set foreground color to redHellois the text\033[0mresets formatting so later output is normal
This matters in real programming because color helps users quickly understand output. For example:
- red for errors
- yellow for warnings
- green for success
- blue for informational messages
Color improves readability in scripts, command-line tools, deployment logs, test runners, and monitoring output.
One important detail is that terminal color support depends on the environment. Many modern terminals support ANSI codes, but some environments may not behave the same way, especially older Windows terminals or output redirected to files. That is why many developers use libraries that smooth out cross-platform differences.
Mental Model
Think of terminal output like writing on a whiteboard with markers.
- normal
print()writes with the default marker - ANSI escape codes are instructions like “switch to the red marker”
- the reset code means “put the red marker away and go back to the normal one”
If you forget to reset, it is like continuing to write everything in red by accident.
So the flow is:
- send a style instruction
- print the message
- reset the style
That pattern is the core idea behind colored terminal text.
Syntax and Examples
Basic ANSI syntax
print("\033[31mThis is red text\033[0m")
print("\033[32mThis is green text\033[0m")
print("\033[33mThis is yellow text\033[0m")
print("\033[34mThis is blue text\033[0m")
Common foreground color codes
30= black31= red32= green33= yellow34= blue35= magenta36= cyan37= white
Example with reusable variables
RED = "\033[31m"
GREEN = "\033[32m"
YELLOW = "\033[33m"
RESET = "\033[0m"
print(f"{GREEN}Success!{RESET}")
print(f"Warning!")
()
Step by Step Execution
Consider this example:
RED = "\033[31m"
RESET = "\033[0m"
print(RED + "Failed to connect" + RESET)
print("Trying again...")
Step-by-step
-
RED = "\033[31m"- A variable is created containing the ANSI code for red text.
-
RESET = "\033[0m"- Another variable is created containing the reset code.
-
print(RED + "Failed to connect" + RESET)- Python joins three strings together.
- The terminal receives:
- the instruction to switch to red
- the text
Failed to connect - the instruction to reset formatting
- The message appears in red.
-
print("Trying again...")- Because the previous line reset the color, this text appears in the normal terminal color.
What if you forget reset?
RED =
(RED + )
()
Real World Use Cases
Colored terminal output is common in many practical situations.
Command-line tools
A CLI program might use:
- green for successful commands
- red for failures
- yellow for warnings
Example:
print("\033[32mBuild completed\033[0m")
print("\033[31mBuild failed\033[0m")
Log messages in scripts
Automation scripts often color status output so important messages stand out.
- info = blue
- warning = yellow
- error = red
Test runners
When tests pass or fail, color makes results easier to scan.
- passed tests in green
- failed tests in red
Deployment and DevOps scripts
Server setup scripts and deployment tools often use color to separate stages and highlight failures.
Educational tools and demos
Learning scripts sometimes color headings, prompts, or results to make output easier to follow.
Interactive terminal apps
Menus, prompts, and user feedback are often color-coded to improve usability.
Real Codebase Usage
In real projects, developers rarely scatter raw escape codes everywhere. They usually wrap them in helpers or use libraries.
Common patterns
Named constants
RED = "\033[31m"
GREEN = "\033[32m"
RESET = "\033[0m"
This avoids magic strings throughout the codebase.
Helper functions
def success(message):
print(f"\033[32m{message}\033[0m")
def error(message):
print(f"\033[31m{message}\033[0m")
This keeps output consistent.
Guarding color usage
Some applications disable colors when output is redirected to a file or when the environment does not support ANSI formatting.
import sys
USE_COLOR = sys.stdout.isatty()
if USE_COLOR:
print("\033[32mReady\033[0m")
else:
print("Ready")
Validation and error handling
Common Mistakes
Forgetting to reset the color
Broken example:
print("\033[31mError happened")
print("This may still be red")
Fix:
print("\033[31mError happened\033[0m")
print("This is normal again")
Using the wrong escape sequence
Broken example:
print("\033[99mHello\033[0m")
99 is not a standard basic foreground color code.
Fix:
print("\033[34mHello\033[0m")
Assuming color works everywhere
Some terminals or redirected outputs may not show colors correctly.
Safer approach:
import sys
if sys.stdout.isatty():
print("\033[32mDone\033[0m")
else:
()
Comparisons
Raw ANSI codes vs helper libraries
| Approach | Pros | Cons | Good for |
|---|---|---|---|
| Raw ANSI escape codes | No extra dependency, simple for small scripts | Less readable, cross-platform issues | Quick scripts and learning |
colorama | Easier syntax, better Windows support | Extra dependency | Small to medium CLI tools |
rich | Powerful formatting, tables, styled logs, tracebacks | More than needed for simple cases | Full-featured terminal apps |
Foreground vs background colors
| Type | Example code | Meaning |
|---|---|---|
| Foreground color |
Cheat Sheet
Quick syntax
print("\033[31mRed text\033[0m")
Common codes
Foreground colors
30black31red32green33yellow34blue35magenta36cyan37white
Background colors
40black41red42green43yellow44blue45magenta46cyan47white
Styles
FAQ
Can Python print colored text without any library?
Yes. You can print ANSI escape codes directly using normal print() statements.
What is the reset code for terminal colors?
The reset code is \033[0m. It returns text formatting to the terminal default.
Why does my colored text not work in some terminals?
Not all environments handle ANSI codes the same way. Some terminals, IDE consoles, or redirected outputs may ignore them or show raw characters.
Is colorama required for colored text in Python?
No. It is not required, but it is useful for cleaner code and better compatibility, especially on Windows.
Can I change the background color too?
Yes. Use background color codes such as 41 for red background or 44 for blue background.
Can I make text bold or underlined?
Yes. ANSI codes can also apply styles like bold (1) and underline (4), depending on terminal support.
Should I use color in logs written to files?
Usually no. Color codes in files can make logs harder to read. Many programs disable color when output is not going to a terminal.
What is the easiest beginner approach?
Start with raw ANSI escape codes to understand the idea, then use colorama if you want cleaner and more portable code.
Mini Project
Description
Build a small Python terminal status reporter that prints messages in different colors based on their meaning. This mirrors a real command-line tool that shows success, warning, and error states clearly for the user.
Goal
Create a script that prints color-coded status messages for info, success, warning, and error output.
Requirements
- Define reusable color constants for at least four message types.
- Write helper functions to print info, success, warning, and error messages.
- Reset terminal formatting after every message.
- Print a short sequence of sample status messages.
- Make the script still produce readable output if color is disabled.
Keep learning
Related questions
@staticmethod vs @classmethod in Python Explained
Learn the difference between @staticmethod and @classmethod in Python with clear examples, use cases, mistakes, and a mini project.
Catch Multiple Exceptions in One except Block in Python
Learn how to catch multiple exceptions in one Python except block using tuples, with examples, mistakes, and real-world usage.
Convert Bytes to String in Python 3
Learn how to convert bytes to str in Python 3 using decode(), text mode, and proper encodings with practical examples.