0
0
PythonHow-ToBeginner · 4 min read

How to Print with Color in Python Terminal Easily

You can print colored text in the Python terminal by using ANSI escape codes or the colorama library. ANSI codes are special strings that change text color, while colorama makes it easy and works on Windows too.
📐

Syntax

To print colored text using ANSI escape codes, use the pattern \033[codem before your text and \033[0m to reset the color. For example, \033[31m sets the text color to red.

Using colorama, you import color constants and wrap your text with them, then reset color automatically.

python
print('\033[31mThis text is red\033[0m')
Output
This text is red
💻

Example

This example shows how to print colored text using both ANSI escape codes and the colorama library. Colorama is recommended for Windows compatibility.

python
from colorama import init, Fore, Style

# Initialize colorama (needed on Windows)
init()

# Using ANSI escape codes directly
print('\033[32mThis text is green using ANSI codes\033[0m')

# Using colorama constants
print(Fore.BLUE + 'This text is blue using colorama' + Style.RESET_ALL)
Output
This text is green using ANSI codes This text is blue using colorama
⚠️

Common Pitfalls

  • Not resetting color after printing causes all following text to stay colored.
  • ANSI codes may not work on some Windows terminals without colorama.
  • Forgetting to call colorama.init() on Windows can cause no color output.
python
print('\033[31mRed text without reset')
print('This text will also be red')

# Correct way
print('\033[31mRed text with reset\033[0m')
print('This text is normal color')
Output
Red text without reset This text will also be red Red text with reset This text is normal color
📊

Quick Reference

ColorANSI Codecolorama Constant
Black30Fore.BLACK
Red31Fore.RED
Green32Fore.GREEN
Yellow33Fore.YELLOW
Blue34Fore.BLUE
Magenta35Fore.MAGENTA
Cyan36Fore.CYAN
White37Fore.WHITE
Reset0Style.RESET_ALL

Key Takeaways

Use ANSI escape codes or the colorama library to print colored text in Python terminal.
Always reset color after printing to avoid coloring unintended text.
Call colorama.init() on Windows to enable color support.
colorama is recommended for cross-platform compatibility.
ANSI codes are simple but may not work on all terminals without support.