Python How To: Colored text in the terminal

Python Programming

Introduction

In programming, sometimes you need to print colored text to the terminal to make the output more readable or to highlight important information. Python provides several ways to do this.

ANSI Escape Codes

The most common way to print colored text in Python is to use ANSI escape codes. These codes are special sequences of characters that tell the terminal to change the color of the text.

Here’s an example of how to print colored text using ANSI escape codes:

print('\033[1;31;40mHello, World!\033[0m')

This will print “Hello, World!” in red text with a black background.

Let’s break down this code:

  • \033: This is the escape character that tells the terminal to start interpreting the ANSI escape codes.
  • [1;31;40m: This sequence of characters is the ANSI escape code for setting the text color to bright red (1;31) and the background color to black (40).
  • Hello, World!: This is the text to be printed.
  • \033[0m: This sequence of characters is the ANSI escape code for resetting the text color and background color to their default values.

You can customize the color of the text and the background by changing the values in the ANSI escape code. Here are some examples:

# Red text on a white background
print('\033[1;31;47mHello, World!\033[0m')

# Yellow text on a blue background
print('\033[1;33;44mHello, World!\033[0m')

# Green text on a red background
print('\033[1;32;41mHello, World!\033[0m')

Using the termcolor Library

Another way to print colored text in Python is to use the termcolor library. This library provides a simple interface for printing colored text to the terminal.

Here’s an example of how to print colored text using the termcolor library:

python

from termcolor import colored

print(colored("Hello, World!", "red"))

This will print “Hello, World!” in red text.

You can customize the color of the text and the background by passing different values to the colored() function. Here are some examples:

# Yellow text on a blue background
print(colored("Hello, World!", "yellow", "on_blue"))

# Green text on a red background
print(colored("Hello, World!", "green", "on_red"))

# White text on a green background
print(colored("Hello, World!", "white", "on_green"))

Conclusion

Printing colored text to the terminal can make your program output more readable and easier to understand. Python provides several ways to print colored text, including ANSI escape codes and the termcolor library. By using these techniques, you can create colorful and visually appealing programs.

Samples:

ANSI Artwork Image Samples

More References:

Wiki ANSI escape codes

Please follow and like us:

Sign up for my newsletter to receive updates on the best deals, free games and my latest Live Streams.

We don’t spam!

Leave a reply