Adding color to text in the terminal can make output more visually appealing and easier to interpret. Python has several ways to print colored text, from using basic ANSI escape codes to leveraging color packages. In this comprehensive guide, we‘ll explore the various methods for printing colored text in Python.

Overview

Here‘s a quick overview of the techniques we‘ll cover:

  • ANSI escape codes: Add codes like \033[31m directly in strings to color text based on ANSI standards.
  • Colorama: A popular package for cross-platform colored terminal text.
  • Termcolor: Color text including custom styling options.
  • Colored: Simple printing of colored text.

We‘ll look at code examples of each method and explain how to install and import necessary packages. By the end, you‘ll have all the tools needed to start adding color to text in your Python applications.

Using ANSI Escape Codes

ANSI escape codes provide a simple way to add color without needing any external libraries. These codes alter the style and color settings for terminal output.

For example, \033[31m sets the foreground text color to red. Resetting color with \033[0m returns text to default terminal colors.

Here‘s some example code showcasing ANSI color codes:

# Red text
print("\033[31mThis is red text\033[0m") 

# Blue background
print("\033[44mText with blue background\033[0m")

# Bold green
print("\033[1;32mBold green text\033[0m")

The output would look like:

ANSI colored text example

The formatting follows this general structure:

\033[STYLE;FOREGROUND;BACKGROUNDm

Where STYLE is an integer code for properties like bold, and FOREGROUND/BACKGROUND specify colors with integers.

So with just basic escape codes, we can color and style text without needing any other dependencies.

The downside is that these codes are not always cross-platform. They may render differently or not at all on certain terminals and operating systems. For wider support, dedicated color packages are a better option.

Installing and Importing Colorama

Colorama simplifies printing colored text to terminals. It handles cross-platform inconsistencies and complexities behind the scenes.

To install:

pip install colorama

Then import it:

from colorama import init
init()

The init() call initializes colorama for use in the Python session.

Colorama has properties like Fore and Back for setting foreground and background colors:

from colorama import init, Fore, Back
init()

print(Fore.RED + ‘This is red text‘)
print(Back.GREEN + ‘Green background‘) 

It also has Style for resetting styling, Cursor for moving the cursor position, and other helpful functions.

We don‘t need to worry about inserting special escape codes everywhere. Colorama handles that internally.

Printing Colored Text with Termcolor

Termcolor is another popular package specifically for printing colored terminal text.

Install it with:

pip install termcolor

The colored() function handles most text coloring needs:

from termcolor import colored

text = colored(‘Red text‘, ‘red‘)
print(text)

text2 = colored(‘Yellow text‘, ‘yellow‘, attrs=[‘bold‘])
print(text2)

We pass the text as the first argument, then the color, and optionally a list of text styles.

Termcolor has color names like ‘blue‘, ‘magenta‘, etc. making it convenient for basic usage.

We can also specify foreground and background colors separately:

colored_text = colored(‘Text‘, ‘grey‘, ‘on_blue‘)

Where the second argument is foreground and the third sets the background.

Using the Colored Package

The colored package provides simple functions for modifying text styles.

After installing with pip, import fg() and attr() to set colors and attributes:

from colored import fg, attr

print(fg(1) + ‘This is red‘ + attr(0))

fg() accepts integer codes mapping to colors, while attr() sets properties like bold, underline, reverse, etc. Passing 0 to attr() resets styling.

Here‘s an example showcasing a few text colors:

text = ‘Sample text‘

print(fg(1) + text + attr(0)) # Red 
print(fg(2) + text + attr(0)) # Green
print(fg(3) + text + attr(0)) # Yellow

The colored package has great support for 256 color terminals as well. It‘s simpler than Colorama or Termcolor while still flexible.

Selecting Colors

Text colors can be specified in different ways depending on the package:

  • Color names: For common colors like ‘red‘, ‘blue‘ etc.
  • Integer codes: Values from 0-255 mapping to colors.
  • Hex codes: String hex codes like ‘#aabbcc‘.

Colorama and Termcolor allow selecting colors by name. Colored and ANSI use integer codes.

Here are some examples of different color selection approaches:

# By name 
colored(‘Text‘, ‘magenta‘)

# Integer code
print(fg(93) + ‘Text‘ + attr(0)) 

# Hex 
print(Fore.CYAN + ‘Text‘)

Make sure to review docs for packages to see available color selection formats.

Not all terminals support 256 colors, so simpler is sometimes better.

Resetting Styles

It‘s important to reset color and style changes after applying them. This avoids unintended styling bleeding into other text outputs.

Here are some examples of resetting for the packages we covered:

ANSI

print("\033[0mReset styles")

Colorama

print(Style.RESET_ALL + "Reset!")

Termcolor

No explicit reset needed. Styles apply only to the text passed to colored().

Colored

print(attr(0) + "Reset text") 

Get in the habit of resetting styles and you‘ll avoid tricky bugs!

Creating Reusable Color Functions

We can wrap text coloring code in functions to reuse the same styles in many places:

from colorama import Fore

def red_text(text):
    return Fore.RED + text + Fore.RESET

print(red_text(‘Warning!‘))
print(red_text(‘Error!‘))

Defining color functions helps reduce duplication in code.

A class can also encapsulate reusable styling:

from termcolor import colored

class Style:

    @staticmethod
    def danger(text):
        return colored(text, ‘red‘, attrs=[‘bold‘])

    @staticmethod
    def success(text):
        return colored(text, ‘green‘, attrs=[‘bold‘])

print(Style.danger(‘Error!‘))
print(Style.success(‘Success!‘))

Here we defined danger() and success() methods that style text consistently. Classes offer more flexibility to extend styling capabilities.

Advanced Color and Style Combinations

By mixing colors, styles, and resets together, we can create complex colored text outputs.

Here‘s an example with Colorama:

from colorama import Fore, Back, Style, init
init()

print(Fore.BLACK + Back.MAGENTA)
print(Style.BRIGHT + Fore.BLUE + ‘Blue text!‘ + Style.RESET_ALL)
print(Style.DIM + Fore.WHITE + Back.RED + ‘Faded white, red background‘ + Style.RESET_ALL)

And with Termcolor:

from termcolor import colored

 danger_text = colored(‘DANGER!‘, ‘red‘, attrs=[‘reverse‘, ‘blink‘])
print(danger_text)

blue_text = colored(‘Info‘, ‘blue‘, attrs=[‘dark‘]) 
print(blue_text)  

Termcolor, Colored, and Colorama all provide attrs parameters for passing in a list of text styles to combine. Play around with mixing colors and effects for custom styling.

Optimizing Performance When Printing Colored Text

Applying colors and styles comes at a small cost in performance. There‘s some overhead in parsing the color codes and configuring terminal output.

We can optimize performance by only coloring text when needed rather than all terminal output. Here are some tips:

  • Don‘t overuse colors just for the sake of it
  • Color primarily informational or warning messages
  • Only use color on CLI apps intended for human viewing
  • Avoid coloring log files and data processing scripts
  • Use an environment variable to toggle coloring on/off

Also try to minimize mixing too many styles and colors in single print statements.

Simple and targeted usage of color maximizes impact while keeping performance optimized.

Testing Colored Text in Python

It helps to test colored text code without constantly running the script. The built-in REPL provides a convenient way to try style snippets.

Here‘s an example session testing some colored text with Termcolor:

>>> from termcolor import colored
>>> danger_text = colored(‘DANGER‘, ‘red‘, attrs=[‘blink‘])
>>> print(danger_text)

The REPL lets us quickly try small pieces of code using the packages we imported.

We can also use Jupyter notebooks to prototype coloring code and immediately see rendered output. This feedback loop helps build an intuition for what combinations work best.

Don‘t forget to try your code in actual terminals as well! The REPL and notebooks don‘t always accurately represent final rendering.

Examples of Using Colored Text in Python Applications

Let‘s explore some real-world examples applying colored text.

Coloring Console Messages

It‘s common to print console messages to users in CLI tools and apps. We can color these messages for increased scannability:

from termcolor import colored
import sys

def status(text):
    print(colored(text, ‘blue‘))

status(‘Downloading data...‘) 
sys.stdout.flush() # Force print

# Rest of script

Termcolor helps key status messages stand out.

Highlighting Warnings

Highlight warnings and errors to users with color:

from colorama import Fore 

if not enough_disk_space:
    print(Fore.YELLOW + "Warning! Low disk space." + Fore.RESET)

Bright colors make it hard to ignore important warnings.

Logging With Color coding

Color can indicate message priority in log files:

from colored import fg
import logging

logging.basicConfig(level=logging.INFO)

logger = logging.getLogger(‘app‘)

logger.info(fg(2) + "Application starting up" + attr(0)) # Green = info
logger.warning("Library not found") # Default color = warn

Here color helps debug issues by marking log priority visually.

Plotting With Colored Lines

Plotting libraries like Matplotlib support custom colored lines:

import matplotlib.pyplot as plt

plt.plot([1,3,5], c=‘r‘) # Red line
plt.plot([2,4,6], c=‘g‘) # Green line 
plt.show()  

So colored text concepts apply to graphing applications as well.

Styling CLI Tool Output

If developing CLI apps, judiciously use color for organizing output:

from colored import attr, fg   

print(fg(64) + "Users:" + attr(0))
print(fg(63) + "[alice, bob, charlie]" + attr(0)) 

print(fg(64) + "Stats:" + attr(0))
print(fg(63) + "Reported 129 metrics today" + attr(0))

Color distinguishes major output sections for better readability.

Conclusion

After reading this guide, you should have a good grasp of options for printing colored terminal text using Python.

Key takeaways include:

  • ANSI escape codes provide platform-independent coloring but limited formatting.
  • Colorama and Termcolor are the most fully-featured packages for text styling.
  • Optimizing performance comes down to only using color when it really enhances output.
  • Test small pieces of color code in the REPL as you build up functionality.
  • Look for opportunities to colorize output and messages in all types of Python applications.

The best way to improve is try the examples for yourself. Use different color and style combinations. See what catches your eye and conveys meaning effectively to the end user.

Soon you‘ll be expertly wielding color formatting to craft beautiful command line interfaces in Python. Happy coding!

Similar Posts