PROGRAMMING | PYTHON
Pythonic Aesthetics — Enhancing Terminal Readability with Color
How to Print Colored Text in Python
Enhancing command-line output is crucial to improve readability in terminal applications, helping developers quickly interpreting information. In the terminal, where execution results and logs are often displayed, incorporating colors can help differentiate between different elements or highlight errors and successes. This is particularly relevant not only for terminal-based applications, but also for general debugging and logging.
The goal of this article is to delve into techniques and libraries that can empower you, as a Python developer, to add colors to your console printing. By doing so, this article aims to provide you with the relevant insights to enhance the visual representation and readability of your output, making it not only more aesthetically pleasing but also ensuring a personalized and improved user experience. 🐍🎨
Basics of Python Printing
The ‘print’ function in Python is fundamental for displaying information in the console. It allows you to output text, variables, or expressions easily, like our very dear “Hello World!”.
# Simple text print
print('Hello World!')
# Simple variable print
str = 'Hello World!'
print(str)
# Simple expression print
print('Hello' + ' ' + 'World' + '!')
You can also print multiple items by separating them with commas or even customize the end character with the ‘end’ parameter.
# Print multiple items by spearating them with commas
print('Hello', 'World', '!')
# Customize the print's end character ('\n' by deafult)
print('Hello World', end='!')
While these basics are crucial, there’s a need for better formatting and visual cues in console printing. Clear and well-formatted output, especially when enhanced with colors, improves the overall readability of the information presented in the terminal.
ANSI Escape Codes
The fundamental elements when adding color to the terminal are ANSI escape codes. These codes, universally recognized by most terminals, are sequences of characters that, when embedded in a string, instruct the terminal to perform specific actions, namely to change text or background color.
The magic begins with the prefix ‘\033[’, signaling the start of an escape sequence. To paint our text with a different color, we would use ‘\033[<code>m’. For instance, the sequence ‘\033[31m’ turns any text succeeding it to red. Likewise, you can also change the background color for your text by using different codes, for instance ‘\033[44m’ sets the background to blue.
Note: Don’t forget to reset the styles you apply by introducing the default style sequence code ‘\033[0m’.
# Print text in red
print('\033[31mHello World but Red!\033[0m')
# Print text with a blue background
print('\033[44mHello World but on Blue!\033[0m')
# Print text in red with a blue background
print('\033[31m\033[44mHello World but Red on Blue!\033[0m')
Here are some codes to get you started exploring, combining foreground and background color codes, and experimenting with different text formatting:
Using Third-Party Libraries
Now that we’ve covered the fundamentals to terminal coloring, it’s time to elevate your Python console printing game by exploring some popular third-party libraries.
Two notable contenders in this realm and that we’ll take a look at are Colorama and Termcolor. These libraries provide a more user-friendly and expressive way to infuse colors into your code output, simplifying the overall process and enhancing code readability.
Colorama
Colorama is a cross-platform library designed to make colored terminal text a breeze. It abstracts the ANSI escape code complexities, allowing you to focus on the colors and styles. To get started, install Colorama using:
pip install colorama
Now, let’s bring the console to life with some vivid examples:
from colorama import Fore, Back, Style, init
# Initialize Colorama
init(autoreset=True)
# Print text in red
print(Fore.RED + 'Hello World but Red!' + Style.RESET_ALL)
# Print text with a blue background
print(Back.BLUE + 'Hello World but on Blue!' + Style.RESET_ALL)
# Print text in red with a blue background
print(Fore.RED + Back.BLUE + 'Hello World but Red on Blue!' + Style.RESET_ALL)
Termcolor
Termcolor is another great library that simplifies colored output. Install it using:
pip install termcolor
Let’s play with some Termcolor magic:
from termcolor import colored
# Print text in red
print(colored('Hello World but Red!', 'red'))
# Print text with a blue background
print(colored('Hello World but on Blue!', 'on_blue'))
# Print text in red with a blue background
print(colored('Hello World but Red on Blue!', 'red', 'on_blue'))
Practical Examples
This section presents a common practical application where colored output can significantly improve readability, namely in displaying logging or status update messages with varying levels of information: Success, Warning, Error, and Informational.
from termcolor import colored
def log_message(message, level):
if level == 'info':
# Print informational message in blue
print(colored('INFO: ' + message, 'blue'))
elif level == 'warning':
# Print warning message in yellow
print(colored('WARNING: ' + message, 'yellow'))
elif level == 'error':
# Print error message in red
print(colored('ERROR: ' + message, 'red'))
elif level == 'success':
# Print success message in green
print(colored('SUCCESS: ' + message, 'green'))
# Print with different levels of information
log_message('Hello World!', 'info')
log_message('Hello World!', 'warning')
log_message('Hello World!', 'error')
log_message('Hello World!', 'success')
By strategically applying color to different types of messages, you can enhance the readability of your console output, making it easier to spot errors, acknowledge successful operations, and differentiate important information.
Tips and Best Practices
Before finishing up, I would like to leave you with some tips and best practices on how to more effectively use colors for your console outputs to avoid visual clutter and maintain readability:
- Prioritize Key Information: Use colors for crucial messages like errors or successes. Maintain consistency to aid quick recognition
- Avoid Overuse: Resist coloring every piece of text to prevent visual clutter. Limit colors to key elements for a cleaner output
- Consider Accessibility: Ensure your color choices accommodate users with color vision deficiencies. Add alternative cues for a broader audience
- Test with Different Themes: Colors may vary in different terminal themes. Test your output across themes to guarantee readability
- Document Color Conventions: If working collaboratively, a best practice would be to document color meanings to maintain consistency and aid project understanding
Conclusion
To sum up, utilizing colored text on your Python application’s terminal output can not only add a touch of visual elegance, but also elevate the functionality and readability of your projects. As we navigated through the essentials of Python printing, unraveling the intricacies of ANSI escape codes and highlighting some third-party gems such as Colorama and Termcolor, I hope that you, as a Python developer, have gained a fundamental understanding of how to breathe life into terminal text with different text coloring styles. I also suggest you keep the tips and best practices that were presented in mind, as these can help ensure that your console output remains clean and readable.
And with that, farewell monochromatic and challenging-to-decode text. Welcome, aesthetic and markedly-more-readable output! 👨💻🖌️