How to print colored text in Python
Learn how to print colored text in Python. This guide covers various methods, tips, real-world uses, and how to debug common errors.

Colored text in Python makes terminal output more readable and engaging. It's a simple way to highlight important information, differentiate message types, and improve the overall user experience.
In this article, we'll cover several techniques to add color to your text. You'll find practical tips for implementation, see real-world applications, and get advice to debug common issues effectively.
Using ANSI escape sequences directly
print("\033[31mRed Text\033[0m")
print("\033[32mGreen Text\033[0m")
print("\033[34mBlue Text\033[0m")--OUTPUT--Red Text
Green Text
Blue Text
ANSI escape sequences are special character strings that most terminals recognize as commands rather than printable text. The \033[ part, known as the Control Sequence Introducer, tells the terminal to expect a formatting command instead of characters to display.
- The code
31msets the text color to red. Different numbers correspond to different colors and styles. - The sequence
\033[0mresets all formatting. It’s crucial to include this at the end. If you don't, all subsequent text in your terminal will remain colored.
Common color libraries
If managing raw ANSI codes feels cumbersome, several Python libraries can simplify the process of adding color and style to your terminal output.
Working with the colorama library
from colorama import Fore, Style, init
init() # Initialize colorama
print(Fore.RED + "Red text" + Style.RESET_ALL)
print(Fore.GREEN + "Green text" + Style.RESET_ALL)
print(Fore.YELLOW + "Yellow text" + Style.RESET_ALL)--OUTPUT--Red text
Green text
Yellow text
The colorama library offers a more intuitive way to handle terminal colors by wrapping ANSI escape codes in simple constants. Before you can use it, you must call init() to properly set up the terminal hooks, which is especially important for Windows compatibility and managing system dependencies.
- The
Foreobject contains constants for foreground colors, likeFore.REDandFore.GREEN. Style.RESET_ALLis used to reset the text formatting, ensuring that subsequent output isn't unintentionally colored.
Printing colors with termcolor
from termcolor import colored
print(colored('Hello, World!', 'red'))
print(colored('Python is fun', 'green'))
print(colored('Colored text is awesome', 'blue', attrs=['bold']))--OUTPUT--Hello, World!
Python is fun
Colored text is awesome
The termcolor library offers a straightforward, function-based approach. Its main function, colored(), wraps your text and applies formatting in one go, which can feel more direct than other methods.
- The first argument is the text string you want to color.
- The second argument is the color, specified as a simple string like
'red'or'green'. - You can also apply additional styles, like
'bold', by passing a list to the optionalattrsparameter.
Rich text formatting using the rich library
from rich import print as rprint
rprint("[red]This is red text[/red]")
rprint("[green]This is green text[/green]")
rprint("[bold blue]This is bold blue text[/bold blue]")--OUTPUT--This is red text
This is green text
This is bold blue text
The rich library is a powerful tool for creating rich text and beautiful formatting in the terminal. It uses a simple markup syntax, similar to BBCode, where you wrap text in tags like [red] and [/red]. It's common to import its print function as rprint to avoid conflicts with Python's built-in function.
- You define colors and styles directly within the string using tags.
- You can combine styles, like
[bold blue], for more complex formatting.
Advanced coloring techniques
For situations where pre-built libraries don't offer enough flexibility, you can write your own logic to unlock a wider range of colors and effects.
Creating a custom color class
class Colors:
RESET = '\033[0m'
RED = '\033[91m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
print(f"{Colors.RED}Warning!{Colors.RESET} {Colors.GREEN}Success{Colors.RESET}")--OUTPUT--Warning! Success
Creating a custom Colors class is a practical way to organize ANSI escape codes into a single, reusable structure. This approach centralizes your color definitions, making your code cleaner and more maintainable. You can then access each color using simple dot notation, like Colors.RED, which is far more readable.
- Each color is defined as a class attribute, such as
REDorGREEN, holding its specific ANSI code string. - The
RESETattribute is essential for returning the terminal to its default state after you've printed colored text.
Using RGB and 256 color codes
def rgb(r, g, b): return f"\033[38;2;{r};{g};{b}m"
print(f"{rgb(255, 100, 100)}Light Red{rgb(100, 255, 100)} Light Green")
print(f"\033[38;5;208mOrange Text (256 color code)")
print(f"\033[0m") # Reset--OUTPUT--Light Red Light Green
Orange Text (256 color code)
For more granular control, you can use ANSI codes that support a wider spectrum of colors. This allows you to move beyond the standard named colors and specify precise shades for your memory-efficient terminal output.
- True Color (RGB): The sequence
\033[38;2;r;g;bmsets the foreground color using specific Red, Green, and Blue values. The example’srgb()function is a convenient helper that constructs this string for you. - 256 Colors: The format
\033[38;5;nmselects a color from a predefined 256-color palette, wherenis the color’s index number.
Creating rainbow text with string manipulation
rainbow = ['\033[91m', '\033[93m', '\033[92m', '\033[94m', '\033[95m', '\033[96m']
text = "Rainbow Text"
rainbow_text = ''.join(rainbow[i % len(rainbow)] + char for i, char in enumerate(text))
print(rainbow_text + '\033[0m')--OUTPUT--Rainbow Text
You can create dynamic effects like rainbow text by applying a different color to each character in a string. This technique combines a list of ANSI color codes with a loop that cycles through them as it builds the final output using the join method.
- The code iterates over the input string using
enumerate()to access each character and its index. The enumerate function is perfect for this task since we need both the character and its position. - The modulo operator (
%) in the expressioni % len(rainbow)ensures the colors from therainbowlist are applied sequentially, wrapping around once the list ends. - Finally,
''.join()assembles the individually colored characters into a single, vibrant string ready for printing.
Move faster with Replit
Replit is an AI-powered development platform that comes with all Python dependencies pre-installed, so you can skip setup and start coding instantly. This lets you move from learning individual techniques, like coloring terminal text, to building complete applications.
With Agent 4, you can describe the tool you want to build, and it will handle the code, databases, APIs, and deployment. Instead of just piecing together color codes, you can build a fully functional app that uses them:
- A real-time server status monitor that uses red, green, and yellow text to display whether services are online, offline, or pending.
- A custom log file formatter that parses raw logs and highlights errors, warnings, and success messages for quick debugging.
- A command-line utility that generates color-coded diffs between two text files, making it easier to spot changes at a glance.
Simply describe your app, and Replit will write the code, test it, and fix issues automatically, all within your browser.
Common errors and challenges
Even with helpful libraries, you might run into a few common issues when adding color to your terminal output. Using try and except blocks can help you handle these errors gracefully.
When using colorama, forgetting to call init() is a frequent oversight, especially for Windows users. This function hooks into your terminal to ensure ANSI escape codes are interpreted correctly. Without it, you might see raw codes like \033[31m printed instead of colored text.
Another common problem is "color bleed," where your terminal text remains colored after your script finishes. This happens when you forget to reset the formatting. Always end your colored string with Style.RESET_ALL or the equivalent ANSI code \033[0m to return the terminal to its default state.
With the rich library, issues often arise from improperly nested markup tags. Since it uses a syntax similar to HTML, you must close tags in the reverse order you opened them. For example, [bold][red]text[/red][/bold] is correct, while closing the bold tag before the red tag would lead to formatting errors.
Fixing terminal color compatibility with init() in colorama
Forgetting to call colorama's init() function is a frequent pitfall, particularly on Windows. Without it, your terminal may not interpret the color commands correctly, leading to garbled output. The following code snippet shows what this looks like in practice.
from colorama import Fore
print(Fore.RED + "Red Text")
print(Fore.GREEN + "Green Text") # May not work in Windows Command Prompt
This code prints raw escape codes directly to the screen because it lacks the init() call needed to interpret them as colors. See how a small addition in the next example corrects this behavior.
from colorama import init, Fore
init() # Initialize colorama for cross-platform compatibility
print(Fore.RED + "Red Text")
print(Fore.GREEN + "Green Text") # Now works on all platforms
The fix is simple: just call init() once at the start of your script. This function configures your terminal to correctly interpret ANSI color codes, which is especially important for Windows compatibility. By adding this single line, you ensure that expressions like Fore.RED are translated into actual colors instead of being printed as raw text. It's a good habit to include init() whenever you use colorama to avoid unexpected output.
Resolving color persistence with proper Style.RESET_ALL codes
A common issue is “color bleed,” where text remains colored even after you intended it to stop. This happens when you don't explicitly reset the terminal's formatting. The following code demonstrates how easily this can occur if you're not careful.
from colorama import Fore
print(Fore.RED + "This text is red")
print("This text should be normal but is still red")
The first print statement sets the terminal's color to red, but it never tells the terminal to switch back. As a result, the color “bleeds” into the next print statement. The following example demonstrates the simple correction.
from colorama import Fore, Style
print(Fore.RED + "This text is red" + Style.RESET_ALL)
print("This text is normal")
The fix is to append Style.RESET_ALL to your string. This command tells the terminal to revert to its default settings immediately after printing the colored text. By adding it to the end of the first print statement, you ensure that only "This text is red" appears in red. The next line prints normally, preventing the color from bleeding into subsequent output. It's a crucial step to keep your terminal output clean and predictable.
Fixing nested color markup in the rich library
The rich library’s markup syntax requires you to close every tag you open, much like HTML. If you forget a closing tag, the style can unexpectedly spill over into subsequent lines. The code below shows what happens when a color tag is left open.
from rich import print as rprint
rprint("[red]This is red [blue]and this is blue")
rprint("This may still be blue")
Because the [blue] tag isn't closed, the blue formatting leaks into the next line. The following example demonstrates how to fix this by properly nesting and closing the tags.
from rich import print as rprint
rprint("[red]This is red [blue]and this is blue[/blue][/red]")
rprint("This is normal text")
The fix is to close tags in the reverse order they were opened. In the corrected example, [blue] is closed before [/red] because it was opened inside the red block. This ensures the blue style is contained and doesn't leak into subsequent text. Think of it like stacking plates—you must remove the top one first. This is a common pattern in markup languages, so always check your tag order when nesting styles.
Real-world applications
With the common pitfalls out of the way, you can apply these coloring techniques to build useful tools like logging systems and dashboards through vibe coding.
Creating a colored logging system with colorama
You can use colorama to build a simple logging function that assigns different colors to message levels like INFO, WARNING, and ERROR, making your logs much easier to scan. This approach is particularly useful when combined with creating a log file for persistent storage.
from colorama import Fore, Style, init
init()
def log(level, message):
if level == "INFO":
print(f"{Fore.BLUE}[INFO]{Style.RESET_ALL} {message}")
elif level == "WARNING":
print(f"{Fore.YELLOW}[WARNING]{Style.RESET_ALL} {message}")
elif level == "ERROR":
print(f"{Fore.RED}[ERROR]{Style.RESET_ALL} {message}")
log("INFO", "System started successfully")
log("WARNING", "Disk space is running low")
log("ERROR", "Failed to connect to database")
This code creates a custom log() function that wraps colorama’s features for structured output. The function takes a level and a message, then uses an if/elif block to determine which color to apply based on the level string.
"INFO"messages are colored blue usingFore.BLUE."WARNING"messages are colored yellow withFore.YELLOW."ERROR"messages are colored red withFore.RED.
Each call to print() uses an f-string to combine the color, the level name, and the message, ensuring Style.RESET_ALL is included to prevent color bleed. Understanding f-string formatting is essential for building dynamic colored text displays.
Building a terminal dashboard with colored metrics using rich
The rich library excels at creating visual dashboards right in your terminal, where color can make key metrics instantly understandable. By combining features like the Panel object for layout with simple conditional logic, you can build an effective status monitor. This approach uses color-coded bars to provide a quick visual summary of system health, changing from green to yellow to red as values increase.
from rich.console import Console
from rich.panel import Panel
from rich import box
console = Console()
data = {"CPU": 45, "Memory": 72, "Disk": 89}
for name, value in data.items():
color = "green" if value < 60 else "yellow" if value < 85 else "red"
bar = "█" * (value // 5) + " " * (20 - value // 5)
content = f"{name}: {value}%\n[{color}]{bar}[/]"
console.print(Panel(content, box=box.ROUNDED))
This code iterates through a dictionary of system metrics using data.items(). For each metric, it dynamically builds a visual representation to display in the terminal.
- A simple bar graph is created by multiplying the
█character. The bar's length is proportional to the metric'svalue. - The metric name, value, and bar are combined into a single string that uses
rich's markup for styling. - Finally,
console.print()renders this content inside aPanelwith rounded borders, creating a neat, boxed display for each metric.
Get started with Replit
Turn your knowledge into a real tool. Describe what you want to build to Replit Agent, like “a script that formats JSON with colored keys” or “a network latency checker with status colors.”
It will write the code, test for errors, and deploy your app automatically. Start building with Replit.
Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.
Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.



