Print Colored Text in Python

Doug Creates
AI Does It Better
6 min readMar 20, 2024

--

Printing colored text in Python involves using third-party libraries like colorama to manipulate terminal output, enabling developers to enhance readability and differentiate information through colors.

This is a recipe from PythonFleek. Get the free e-book today!

Code

Utilize colorama for vibrant Python console texts. Within Jupyter, try this.

import sys
def print_colored(text, color, end='\n'):
colors = {'red': '\x1b[31m', 'green': '\x1b[32m', 'yellow': '\x1b[33m', 'blue': '\x1b[34m'}
reset = '\x1b[0m'
sys.stdout.write(colors.get(color, '') + text + reset + end)

print_colored('red text', color='red')
print_colored('green text', color='green')
print_colored('blue text', color='blue')

This outputs colored text, but there are more ways below.

Explanation

Developers looking to improve readability and differentiate information in terminal outputs.

Importing sys: import sys is used to access the sys.stdout.write function for printing.
Defining print_colored: def print_colored(text, color): defines a function to print colored text.
Color codes: A dictionary colors maps color names to their ANSI escape codes.
Reset code: reset = '\x1b[0m' resets the color to default after printing.
Printing with color: sys.stdout.write prints the text in the specified color and resets it.
Customizable function: Users can add more colors to the colors dictionary.
No external libraries: This method doesn't require any external libraries, using only Python's standard library.
Direct control over output: Offers more control over the output formatting compared to the print function.
Compatibility: ANSI codes are widely supported but may not work in some Windows terminals without additional configuration.
Advanced usage: More suitable for users with some Python experience and understanding of ANSI codes.

Enhancing Python Outputs with Colored Text

Discover how to make your Python terminal outputs pop with vibrant colors!

Why: Using colored text can significantly enhance the readability of terminal outputs, making it easier to distinguish between different types of information.

Install: pip install colorama

Demo 1

Implement colorama for vibrant terminal texts, elevating data visualization for expert statisticians.

# Demo program to showcase printing colored text in Python using colorama and termcolor libraries
# Importing necessary libraries
import colorama
from colorama import Fore, Style
from termcolor import colored
colorama.init(autoreset=True) # Initializes colorama to autoreset colors after each print statement

# Function to print colored text using colorama
def print_with_colorama():
print(Fore.RED + 'This is red text using colorama')
print(Fore.GREEN + 'This is green text using colorama')
print(Style.BRIGHT + Fore.BLUE + 'This is bright blue text using colorama')

# Function to print colored text using termcolor
def print_with_termcolor():
print(colored('Hello, World!', 'red'))
print(colored('Python is cool!', 'green'))
print(colored('Python is cool!', 'blue', 'on_white', ['underline']))

# Demonstrating the use of colorama
print('Demonstrating colorama library:')
print_with_colorama()

# Demonstrating the use of termcolor
print('\nDemonstrating termcolor library:')
print_with_termcolor()

# This demo showcases two popular methods for printing colored text in Python terminals. The first part uses the colorama library to directly manipulate text color and style. The second part demonstrates the termcolor library, which provides a simpler interface for coloring text, including options for background color and text attributes like underline.

Demo 2

# Demo 2: Using colorama for colored text
import colorama
from colorama import Fore, Style

colorama.init(autoreset=True) # Initializes colorama and autoresets color
print(Fore.RED + 'This is red text')
print(Fore.GREEN + 'This is green text')
print(Style.BRIGHT + Fore.BLUE + 'This is bright blue text')

Invoke colorama for vibrant Python console outputs.

# Example using colorama to print colored text in Python
import colorama
from colorama import Fore, Style
colorama.init(autoreset=True) # Initializes colorama and autoresets color

# Function to print messages in different colors
def print_colored_message(message, color):
if color == 'red':
print(Fore.RED + message)
elif color == 'green':
print(Fore.GREEN + message)
elif color == 'blue':
print(Fore.BLUE + message)
else:
print(message) # Default to no color

# Example usage
print_colored_message('This is a warning message.', 'red')
print_colored_message('This is an informational message.', 'green')
print_colored_message('This is just a regular message.', 'none')

# This function demonstrates how to use colorama to print text in different colors.
# It's a simple way to enhance the readability of terminal output by differentiating
# information through colors. The function takes a message and a color as arguments,
# and prints the message in the specified color.

Case Study

Suppose we were tasked with enhancing the logging system of a Python-based application to make it more readable and intuitive for developers during debugging sessions. The team decided to incorporate colored text outputs to differentiate between various log levels (e.g., INFO, WARNING, ERROR). They chose to use the colorama library for its simplicity and cross-platform compatibility. After installing the library using pip install colorama, they wrapped their logging messages with colorama's color codes. For instance, ERROR messages were printed in red, WARNING in yellow, and INFO in green. This implementation significantly improved the debugging process, making it easier for developers to spot and prioritize issues based on the color-coded log messages.

Pitfalls

Compatibility: Ensure the terminal or console used supports ANSI escape sequences, as colorama works by converting these sequences into the appropriate text colors.
Overuse of Colors: Using too many colors or non-contrasting colors can lead to confusion rather than clarity. Stick to a consistent and meaningful color scheme.
Performance: Be mindful of the potential impact on performance when excessively using colored text in high-volume logging.

Tips for Production

Consistency: Define a standard color scheme for different types of messages (e.g., logs, errors, warnings) and stick to it across the application to maintain consistency.
Testing: Test the color output on different platforms and terminals to ensure compatibility and readability.
Optimization: Use colorama’s init() function at the start of your script to ensure optimal performance and compatibility.

Demo 3

# Demo 3: Using termcolor for colored text
from termcolor import colored

# Print 'Hello, World!' in red
print(colored('Hello, World!', 'red'))

# Print 'Python is cool!' in green and then in blue with underline
print(colored('Python is cool!', 'green'))
print(colored('Python is cool!', 'blue', 'on_white', ['underline']))

# First argument is the text, second is the text color, third is the background color, and fourth is the list of attributes

Recommended Reading

Python (programming language): A high-level, interpreted programming language known for its ease of learning and versatility. https://en.wikipedia.org/wiki/Python_(programming_language)
ANSI escape code: A standard for in-band signaling to control cursor location, color, and other options on video text terminals. https://en.wikipedia.org/wiki/ANSI_escape_code
Colorama: A popular Python module that simplifies the task of printing colored text in terminals. https://en.wikipedia.org/wiki/N/A

Encore

Throughout this exploration, we’ve delved into the vibrant world of printing colored text in Python, a technique that significantly enhances the readability and visual appeal of terminal outputs. By leveraging libraries like colorama and termcolor, we’ve seen firsthand how straightforward it can be to introduce color into our console applications, making them more intuitive and engaging for users. From the basic implementation of colorama to more advanced uses in logging and data visualization, the potential applications are vast and varied. As we continue to develop and refine our Python projects, incorporating colored text will undoubtedly remain a valuable tool in our arsenal for creating more accessible and user-friendly interfaces.

Demo 4

# Demo 4: Combining colorama with custom functions for more complex use cases
import colorama
from colorama import Fore, Back, Style

colorama.init(autoreset=True)

def print_warning(message):
print(Fore.YELLOW + Style.BRIGHT + message)
def print_error(message):
print(Fore.RED + Style.BRIGHT + message)
def print_success(message):
print(Fore.GREEN + message)

# Usage examples
print_warning('Warning: Proceed with caution!')
print_error('Error: Something went wrong!')
print_success('Success: Operation completed successfully!')

# This example shows how to create custom print functions for different message types (warning, error, success) using colorama for colored output.

--

--