How to Print Colored Text in Python

Printing colored text in Python can make your output more engaging and easier to read. Whether you’re highlighting errors, differentiating data types, or simply adding visual flair to your console applications, Python offers simple ways to achieve this.

Understanding ANSI Escape Sequences

At the heart of colored text in Python’s console are ANSI escape sequences. These are special character combinations that your terminal emulator interprets as commands to change text color, style, or other attributes.

An ANSI escape sequence starts with an escape character (represented as 33 or x1b in Python) followed by a specific code within square brackets ([...]). For example, the code 33[31m sets the text color to red.

Basic Color Codes

Here’s a table of commonly used ANSI color codes:

Color Foreground Code Background Code
Black 30 40
Red 31 41
Green 32 42
Yellow 33 43
Blue 34 44
Magenta 35 45
Cyan 36 46
White 37 47

Printing Colored Text using the print() Function

You can directly embed ANSI escape sequences within your print() statements to output colored text:

print("33[31mThis text is red!33[0m")
print("33[44mThis text has a blue background.33[0m")

In these examples, 33[0m resets the color settings to the default.

Using Variables for Readability

For cleaner code, you can store ANSI escape sequences in variables:

RED = "33[31m"
RESET = "33[0m"

print(f"{RED}This is red.{RESET}")

Combining Colors and Styles

You can combine color codes with style codes like bold or underline:

BOLD = "33[1m"
UNDERLINE = "33[4m"

print(f"{BOLD}{UNDERLINE}Important message!{RESET}")

The colorama Library

The colorama library simplifies working with ANSI codes, especially across different operating systems.

from colorama import Fore, Back, Style

print(Fore.RED + 'This text is red in color' + Style.RESET_ALL)
print(Back.BLUE + 'This text has a blue background' + Style.RESET_ALL)

colorama automatically handles platform-specific differences, making your code more portable.

Practical Examples

Highlighting Errors

try:
    # Some code that might raise an error
except Exception as e:
    print(f"{Fore.RED}Error: {e}{Style.RESET_ALL}")

Differentiating Data Types

my_string = "Hello"
my_number = 123

print(f"String: {Fore.GREEN}{my_string}{Style.RESET_ALL}")
print(f"Number: {Fore.BLUE}{my_number}{Style.RESET_ALL}")

Conclusion

Printing colored text in Python is a straightforward way to enhance the visual appeal and clarity of your console output. Whether you choose to use ANSI escape sequences directly or leverage the convenience of the colorama library, a splash of color can make a significant difference in how your code communicates with the user.

FAQs

1. Why isn’t the colored text working on my system?

  • Ensure your terminal emulator supports ANSI escape sequences.
  • Try using the colorama library, which enhances cross-platform compatibility.

2. Can I use custom RGB colors?

  • Standard ANSI escape sequences support a limited color palette.
  • Some terminal emulators may offer extended color options.

3. What is the purpose of Style.RESET_ALL?

  • It resets all text formatting, including color, style, and background, to their defaults.

4. Is it possible to print colored text to a file?

  • ANSI escape sequences are interpreted by the terminal emulator.
  • You would need to use a library that supports writing formatted text to files.

5. Are there any performance implications of using colored text?

  • While generally minimal, excessive use of ANSI escape sequences could introduce slight overhead.

6. How can I learn more about ANSI escape sequences?

  • Search online for “ANSI escape codes” or consult the documentation for your terminal emulator.

7. Are there any other Python libraries for colored text besides colorama?

  • Yes, alternatives like termcolor and rich offer additional features and customization options. You can find tutorials and examples for these libraries on their respective documentation pages. For more advanced terminal formatting and styling, consider exploring libraries like prompt_toolkit or blessed.

Need help with Python or want to explore more advanced coding techniques? Contact us at 0373298888, email [email protected], or visit our office at 86 Cầu Giấy, Hà Nội. Our team is available 24/7 to assist you.