How to add colored text to your Python programs
Not only do they make your programs look professional and easy to read -- they're just fun!
Colored text isn't just a fun way to make your Python programs look nice.
It also makes them look significantly more readable and professional.
In this article, I'm going to show you...
How to add colors to your Python program
How to make them easy to reuse between programs
How to properly color text to make different information stand out
Coloring your text is as simple as encasing the text you want to format in ANSI escape codes.
Effectively, these are any escape sequences formatted as "\033[" followed by the number of the format you want to use.
Here's a list of common formats and their ANSI escape codes:
🔴 RED: \033[31m
🟢 GREEN: \033[32m
🟡 YELLOW: \033[33m
🔵 BLUE: \033[34m
BOLD: \033[1m
ITALIC: \033[3m
CLEAR FORMATTING: \033[0m
To make your text colored, you want to add two escape codes:
One before your text that defines the formatting you want to use
One after your text that clears the formatting
Here's an example line of code that could be used to print a colored line:
# prints a red line of text
print("\033[31m" + "This is a line of text" + "\033[0m")
But I know you don't want to have to memorize and retype these codes every time you want to use them.
Thankfully, there's an easy solution that only requires you to copy/paste a small snippet of code.
All you have to do is create a class with variables that hold the values of these escape codes.
Here is what that might look like:
class colors:
red = '\033[31m'
green = '\033[32m'
yellow = '\033[33m'
blue = '\033[34m'
bold = '\033[1m'
italic = '\033[3m'
clear = '\033[0m'
Now, adding colors would look something like this:
# prints a red line of text
print(colors.red + "This is a line of text" + colors.clear)
Don't forget to clear formatting after each line; otherwise, your formatting will continue for every line of text after the escape code.
Here is how I would recommend you use each formatting option:
⚪️ Use no formatting for general information
🔴 Use red for error messages
🟡 Use yellow for warning messages
🟢 Use green for success messages
🔵 Use blue for important information
⚫️ Use bold/italics for any other information you want to stand out
These options will not only make your programs easier to digest, but they'll also dramatically improve the look and feel of your program.
And as a plus, it's just plain fun!