Programming

How to Print Colored Text in Python Terminal

Learn to print colored text in Python terminal using ANSI escape codes, termcolor, and colorama for python colored print. Cross-platform examples, troubleshooting, and best practices for python print color text.

1 answer 4 views

How do I print colored text to the terminal in Python?

Printing colored text in Python terminals is straightforward using ANSI escape codes for a no-library approach or termcolor and colorama for simpler, cross-platform python colored print. Here’s a quick start: print("\033[91mThis is red!\033[0m")—that \033[0m resets to avoid color bleed. For python colored text that’s reliable on Windows too, install colorama with pip install colorama and use print(Fore.RED + 'Alert!').


Contents


Python Colored Text Basics

Ever stared at a wall of black-and-white terminal output and wished for some visual pop? Python colored text brings logs to life—errors in red, successes in green, warnings in yellow. It grabs attention during debugging or scripts, making output scannable at a glance.

No magic here. Terminals interpret special ANSI escape sequences embedded in your print strings. These aren’t Python-specific; they’re a terminal standard. But Python makes them dead simple to drop in.

Why bother? Imagine running a long script. Colored output flags issues instantly. No more hunting through lines. And yeah, it works in most modern terminals—Linux, macOS, even Windows 10+ with tweaks.

Stack Overflow threads rave about this for quick wins, though libraries shine for bigger projects. Stack Overflow nails the basics: embed codes, print, done. But let’s break it down properly.


ANSI Escape Codes for Python Colored Print

Raw ANSI escape codes? The foundation of python colored print. No installs needed. Just strings with \033[ (escape) followed by a code, then m to apply.

Basic pattern: print("\033[CODEmYour text here\033[0m"). That \033[0m resets everything—crucial, or your next print stays colored. Forget it once, and you’ll curse forever.

Here’s the money table of common codes, pulled from solid guides like GeeksforGeeks and Sentry:

Color/Style Foreground Code Background Code Example
Black 30 40 \033[30mBlack\033[0m
Red 31 41 \033[31mRed\033[0m
Green 32 42 \033[32mGreen\033[0m
Yellow 33 43 \033[33mYellow\033[0m
Blue 34 44 \033[34mBlue\033[0m
Magenta 35 45 \033[35mMagenta\033[0m
Cyan 36 46 \033[36mCyan\033[0m
White 37 47 \033[37mWhite\033[0m
Bold 1 - \033[1mBold\033[0m
Reset 0 - \033[0m

Test it. Fire up your terminal:

python
print("\033[91mBright red alert!\033[0m") # 91 = bright red
print("\033[42mGreen background\033[0m") # 42 = green bg
print("\033[1;34mBold blue\033[0m") # Combine with ;

Bright colors? Add 60 to the code (90-97 for foreground). Real Python demos this perfectly: turn on with 31, off with 0.

Pitfall: Windows Command Prompt pre-10 chokes on these. More on that later. But on Linux/macOS? Instant gratification.

Combine freely. \033[1;31;40mBold red on black\033[0m. Wild, right? StackAbuse walks through combos like a pro.


Termcolor: Simple Python Colored Text

Hate memorizing codes? Enter termcolor. Pip install: pip install termcolor. Boom—named colors.

From Programiz and PyPI:

python
from termcolor import colored

print(colored('Hello, world!', 'red', attrs=['bold']))
print(colored('Success!', 'green'))

Colors: red, green, yellow, blue, magenta, cyan, white. Attrs like ‘bold’, ‘underline’. Resets automatically—no bleed worries.

GeeksforGeeks loves it for beginners. Short. Readable. Your scripts look pro.

Windows? Spotty ANSI support means it might flake. Pair with colorama next section. But for Unix? Chef’s kiss.


Colorama for Cross-Platform Python Print Color Text

Windows users, rejoice. Colorama translates ANSI codes to work everywhere. pip install colorama. Init once:

python
from colorama import init, Fore, Back, Style
init(autoreset=True) # Auto-resets after each print

print(Fore.RED + 'Error!')
print(Fore.GREEN + Back.YELLOW + 'Warning on yellow')
print(Style.BRIGHT + 'Bright normal text')

GeeksforGeeks calls this the cross-platform hero. Fore.RED, Back.BLUE, Style.DIM—intuitive.

Autoreset? Magic. No manual \033[0m. Strip colors for logs? colorama.ansi.ansi_ljust() helpers exist.

Stack Overflow warns: older Windows needs enabling. But Windows 10 Terminal? Flawless. Run scripts anywhere, same output.


Advanced Libraries like Rich

Outgrown basics? Rich crushes it for tables, progress bars, markdown in terminals. pip install rich.

python
from rich.console import Console
from rich import print as rprint

console = Console()
console.print("Red text", style="red bold")
rprint("[green]Green![/green]")

Themes, syntax highlighting, live updates. Spark by Examples compares it to ANSI—Rich wins for apps.

Other gems: ansi package for code wrappers, ansicolors for partial funcs. PyPI pages demo:

python
from colors import color
red_bold = color(fg='red', style='bold')
print(red_bold('Critical!'))

Truecolor (RGB)? ANSI \033[38;2;r;g;bm. Rich handles it natively. GitHub gists like this one map 256 colors.

When? Logs, CLIs, dashboards. Everyday scripts? Stick simpler.


Troubleshooting Common Issues

Colors not showing? First: terminal supports ANSI? VS Code integrated? Enable “terminal.integrated.gpuAcceleration”.

Windows CMD? Upgrade to PowerShell or Windows Terminal. Or force: colorama.init(convert=True).

Bleeding colors? Always reset. Jakob Bagterp’s guide explains: terminals persist until \x1b[0m.

Library fails? Pip reinstall. Virtualenv mismatch? Check.

No color in pipes/redirects? force_color=True in Rich or colorama.

Better Stack has helper funcs:

python
def colored(text, color):
 colors = {'red': '\033[91m', 'green': '\033[92m'}
 return f"{colors.get(color, '')}{text}\033[0m"

print(colored("Red", "red"))

Russians searching “цветной текст в python”? Same tricks—ANSI universal.


Full Examples and Best Practices

Script time. Logger with colors:

python
from colorama import init, Fore
init()

def log(level, msg):
 colors = {'INFO': Fore.CYAN, 'WARN': Fore.YELLOW, 'ERROR': Fore.RED}
 print(f"{colors.get(level, Fore.WHITE)}[{level}] {msg}{Fore.RESET}")

log('ERROR', 'Connection failed')
log('INFO', 'Server up')

Best practices?

  • Reset always.
  • Libraries for teams—readable.
  • Test platforms.
  • Log stripping: Rich’s no_color=True.

Vultr Docs echoes: apply to text, print.

Scale up: CLI tools scream for this. Your next script? Transform it.


Sources

  1. Stack Overflow - How do I print colored text to the terminal?
  2. Print Colors in Python terminal - GeeksforGeeks
  3. Print colored text to terminal with Python | Sentry
  4. Ultimate Guide to ANSI Escape Codes - Colorist for Python
  5. Real Python - ANSI Escape Sequences
  6. Python Program to print colored text to the terminal - Programiz
  7. How to Print Colored Text in Python - StackAbuse
  8. Print Colored Text to the Terminal in Python - Spark By Examples
  9. ansi · PyPI
  10. ansicolors · PyPI
  11. ANSI color codes in Python · GitHub Gist
  12. Better Stack Community - How to print colored text in terminal
  13. Python Program to print colored text to the terminal | Vultr Docs

Conclusion

Python colored text transforms bland terminals into vibrant tools—start with ANSI for speed, level up to termcolor or colorama for polish. Pick based on your setup: raw codes for Linux/mac, libraries for Windows or apps. Experiment, reset religiously, and watch your output shine. Next debug session? You’ll never go back to monochrome.

Authors
Verified by moderation
Moderation
How to Print Colored Text in Python Terminal