🐶
Python

Print Colored Text in Python Terminal

By Filip on 10/05/2024

Learn different methods to print colored text to your terminal using Python, making your scripts more visually appealing and easier to debug.

Print Colored Text in Python Terminal

Table of Contents

Introduction

This article explains how to print colored text to the terminal in Python using ANSI escape sequences. You'll learn how to use ANSI codes directly and how to simplify the process with the 'colorama' library. The article provides examples of common color codes, how to combine colors and styles, and how to reset the color to avoid affecting subsequent output.

Step-by-Step Guide

To print colored text to the terminal in Python, you can use ANSI escape sequences. These are special codes that you embed in your strings to control the formatting and color of the output.

  1. Import the colorama library (optional but recommended): While you can use ANSI codes directly, the colorama library makes it easier to manage colors, especially across different operating systems. Install it using pip:

    pip install colorama

    Then, import it in your script:

    from colorama import Fore, Back, Style
  2. Understand ANSI escape codes: ANSI escape sequences start with \033[ (or its hexadecimal equivalent \x1b[) followed by a code that specifies the color or style, and end with m.

    Here are some common color codes:

    • 30: Black
    • 31: Red
    • 32: Green
    • 33: Yellow
    • 34: Blue
    • 35: Magenta
    • 36: Cyan
    • 37: White

    You can also use these codes for background colors by adding 10 to the foreground color code (e.g., 41 for red background).

  3. Print colored text: To print a colored string, embed the ANSI escape sequence within the string using an f-string:

    print(f"\033[31mThis text is red.\033[0m")

    This will print the text "This text is red." in red. The \033[0m at the end resets the color to the default.

  4. Use colorama for easier color management: With colorama, you can use more readable names for colors and styles:

    print(Fore.RED + "This text is red." + Style.RESET_ALL)

    This achieves the same result as the previous example but is more concise and easier to understand.

  5. Combine colors and styles: You can combine multiple ANSI codes within the same escape sequence to apply both color and style:

    print(f"\033[1;31;40mThis text is bold red on a black background.\033[0m")

    This will print the text in bold red on a black background.

  6. Reset the color: Always remember to reset the color and style at the end of your colored string using \033[0m or Style.RESET_ALL to avoid affecting subsequent output.

By using ANSI escape sequences and optionally the colorama library, you can easily add colors and styles to your terminal output in Python, making it more visually appealing and easier to read.

Code Example

This Python code demonstrates how to print colored text in the console. It shows three examples: using ANSI escape codes directly, using the colorama library for more readable color names, and combining colors and styles with colorama.

# Example 1: Using ANSI escape codes directly

print(f"\033[31mThis text is red.\033[0m")
print(f"\033[32mThis text is green.\033[0m")
print(f"\033[1;34;41mThis text is bold blue on a red background.\033[0m")

# Example 2: Using the colorama library

from colorama import Fore, Back, Style

print(Fore.YELLOW + "This text is yellow." + Style.RESET_ALL)
print(Back.GREEN + "This has a green background." + Back.RESET)
print(Fore.MAGENTA + Back.CYAN + "Magenta text on cyan background" + Style.RESET_ALL)

# Example 3: Combining colors and styles with colorama

print(Fore.RED + Style.BRIGHT + "This text is bright red." + Style.RESET_ALL)
print(Fore.BLUE + Style.DIM + "This text is dim blue." + Style.RESET_ALL)

Explanation:

  • Example 1 demonstrates how to use ANSI escape codes directly within f-strings to change text color and background.
  • Example 2 shows how to achieve the same results using the colorama library, which provides more readable names for colors and styles.
  • Example 3 illustrates how to combine different colors and styles using colorama to create more visually appealing output.

Remember to install the colorama library using pip install colorama before running the second and third examples.

Additional Notes

  • Compatibility: ANSI escape sequences are widely supported by modern terminals and operating systems, but there might be some compatibility issues with older systems.
  • Alternatives to colorama: Other libraries like termcolor and rich offer similar functionality for colored terminal output with additional features.
  • Use Cases: Colored terminal output is helpful for:
    • Error messages and warnings: Highlight important information in red or yellow.
    • Progress bars and status updates: Provide visual feedback during long-running processes.
    • Command-line tools and scripts: Improve readability and user experience.
  • Overuse: Avoid overusing colors and styles, as it can make the output cluttered and difficult to read.
  • Accessibility: Be mindful of users with visual impairments and consider providing alternative ways to convey information besides color.
  • Experimentation: The best way to learn about ANSI escape sequences is to experiment with different codes and combinations.

Additional Tips:

  • You can define your own functions or classes to encapsulate commonly used color and style combinations for easier reuse.
  • Consider using a code editor or IDE that supports syntax highlighting for ANSI escape sequences to make your code more readable.
  • Refer to the documentation of the colorama library or other libraries you choose to use for a complete list of available colors, styles, and features.

Summary

This article provides a concise guide on how to print colored text in your Python terminal output.

Method Description Example Library Required
ANSI Escape Sequences Embed special codes directly into strings to control text formatting and color. print(f"\033[31mThis text is red.\033[0m") No (but recommended)
Colorama Library Simplifies color management with readable names and cross-platform compatibility. print(Fore.RED + "This text is red." + Style.RESET_ALL) Yes (pip install colorama)

Key Takeaways:

  • ANSI Codes: Start with \033[ or \x1b[, followed by color/style codes, and end with m.
    • Color Codes: 30-37 for foreground, 40-47 for background (add 10).
    • Style Codes: 1 for bold, etc.
  • Resetting: Always reset color/style after using ANSI codes with \033[0m or Style.RESET_ALL.
  • Colorama: Offers a more user-friendly way to work with ANSI codes.

By leveraging these techniques, you can enhance the visual appeal and readability of your terminal output in Python.

Conclusion

By following the steps outlined in this article, you can easily add colors and styles to your Python terminal output, making it more engaging and informative. Whether you choose to use ANSI escape codes directly or opt for the convenience of the 'colorama' library, you now have the tools to enhance your terminal applications with vibrant colors and formatting. Experiment with different color combinations and styles to create visually appealing and user-friendly output for your Python programs.

References

Were You Able to Follow the Instructions?

😍Love it!
😊Yes
😐Meh-gical
😞No
🤮Clickbait