How to Print Colored Text in Python

Python is an intuitive and versatile programming language widely used for various purposes such as web development, scientific computing, machine learning, data analysis, etc.

Printing colorful and attractive outputs on the terminal can enhance the user experience and make the output look more appealing.

In this tutorial, we’ll learn how to print colored text in Python in a simple and efficient way.


Introduction to ANSI escape sequences

To print colored text in Python, we need to use ANSI escape sequences.

ANSI escape sequences are a set of characters that are interpreted as control characters by a terminal emulator.

These characters allow us to perform various tasks such as changing the background color, foreground color, and styling of the text, moving the cursor to a specific position on the terminal, clearing the screen, etc.

Printing colored text in Python

To print colored text in Python, we can use the print function along with ANSI escape sequences.

The basic syntax to print colored text in Python is:

print("\033[<style>;<background color>;<foreground color>m<text>\033[0m")

where:

  • style: The style of the text. The options are: 0 (normal), 1 (bold), 4 (underline), 7 (negative).
  • background color: The background color of the text. The options are: 40 (black), 41 (red), 42 (green), 43 (yellow), 44 (blue), 45 (magenta), 46 (cyan), 47 (white).
  • foreground color: The foreground color of the text. The options are: 30 (black), 31 (red), 32 (green), 33 (yellow), 34 (blue), 35 (magenta), 36 (cyan), 37 (white).
  • text: The text to be printed in colored format.
  • It is important to note that the ANSI escape sequences should be enclosed in double quotes (“), not single quotes (‘), to be interpreted as control characters.

Code Examples

Here are some code examples to help you understand how to print colored text in Python:

# Example 1: Print red text
print("\033[31mRed Text\033[0m")

# Example 2: Print bold green text
print("\033[1;32mBold Green Text\033[0m")

# Example 3: Print underlined yellow text on blue background
print("\033[4;33;44mUnderlined Yellow Text on Blue Background\033[0m")

# Example 4: Print negative magenta text
print("\033[7;35mNegative Magenta Text\033[0m")

Conclusion

In this blog post, we have learned how to print colored text in Python using ANSI escape sequences.

Colored text can make the output look more attractive and appealing to the user.

It is important to note that ANSI escape sequences work only in the terminal and not in IDLE or other integrated development environments.

I hope this post was helpful in understanding how to print colored text in Python.