Color text output in Python 3

by Alex
Color text output in Python 3

Python has enough tools to output text to the console in any color. Such output requires little skill, is implemented in a few lines of code, and is used both to highlight important information and to add beauty to text. You can make the text colored in two ways: using the built-in language tools or using libraries. Each method has advantages and disadvantages, there are also subtleties relating to changing the color of text in the Windows console.

Using the language’s built-in tools

In Python, you can format text using ANSI codes. This is a very powerful and handy tool, with its help the programmer can directly determine the color of text. ANSI codes work on most Linux distributions, but are not supported by the Windows operating system console until Windows 10. There is a separate paragraph in the article about how to run on Windows!

On different Linux distributions and on Windows 10, the color of the text created with the same ANSI code may be different. It depends on the console settings, its customization by the user and some other factors.

You can change the color of text with ANSI code in different ways, such as using functions or even writing your own ANSI wrapper class. Using ANSI codes is easy, you just need to know the basic syntax and the codes themselves. Here is an example of the code “33[31m33[43m”:

  • /033 – indicating that some color control code is coming next;
  • [31m – text color (red);
  • [43m is the background color (yellow).

After displaying this in the console, the output will be red on a yellow background. Reset to initial values : 33[0m. Basic codes:

  • 33[0-7m are various effects, such as underline, blink, bold, and so on;
  • 33[30-37m are codes that define the text color (black, red, green, yellow, blue, purple, blue-blue, gray);
  • 33[40-47m – codes defining the background color.

Colors

Color Text Background
Black 30 40
Red 31 41
Green 32 42
Yellow 33 43
Blue 34 44
Purple 35 45
Turquoise 36 46
White 37 47

Effects

Code Value
0 Reset to initial values
1 Bold
2 Faded
3 Italic
4 Underlined
5 Rare blinking
6 Frequent flashing
7 Change the background color with the text color

Functions to call

You can quickly color a string the way you want with functions. You need to give them talking names, pass in a string as an argument and use the correct ANSI code in their body. The approach is convenient because you can declare N functions that format any text in the desired color and use them in all your programs, just import the module. For example, like this: Code:

def out_red(text):
    print("33[31m {}" .format(text))
def out_yellow(text):
    print("33[33m {}" .format(text))
def out_blue(text):
    print("33[34m {}" .format(text))
out_red("Output in red")
out_yellow("Yellow text")
out_blue("blue text")

Result:

We only changed the color of the text, but you can also change the background color and add additional styles. For example, to output the underlined text in white on a blue background, write like this

print("33[4m33[37m33[44m{}33[0m".format("Python 3"))

This is what the output will look like:Functions to call

Notice the line print("33[4m33[37m33[44m{}33[0m".format("Python 3")). Here we did the output as follows:

  • 33[4m – underlined;
  • 33[37m – white lettering;
  • 33[44m – blue background;
  • {} will be replaced by “Python 3”;
  • 33[0m – reset to default values.

How to output colored text to the console on Windows

Linux has built-in ANSI code support by default for the console, while Windows does not. This is because for Linux the console is the main working tool. In Windows, the console is rarely used, so there is no point in embedding such things in it. However, in Windows 10, starting with Threshold 2, the developers have added support for control codes to the console. However, due to the fact that not everyone uses the new OS, you still have to use additional libraries to write console applications with colored text.

So the library colorama supports work with Windows 10! Therefore, its use is recommended.

In order to make the code written using internal means Python 3 or using the termcolor library work on Windows 10, you need to enable ANSI support for stdout in the running console. Youcan do this as follows:

import ctypes
kernel32 = ctypes.windll.kernel32
kernel32.SetConsoleMode(kernel32.GetStdHandle(-11), 7)

Output colored text to the console with colorama

Colorama is the most popular library for outputting colored text in Python 3. Colorama allows you to use ANSI codes not only in Linux, but also in Windows. Using the library’s functions and methods makes it easier to write code and easier to maintain. You no longer need to memorize or copy ANSI codes. The commands are so simple and intuitive that even the average user can do the job. Using a third-party library, such as colorama, does not lead to any negative effects. Before using colorama, it must be installed with the command pip install colorama in the console. Here is an example of using colorama:

import colorama
from colorama import Fore, Back, Style
colorama.init()
print(Fore.RED + 'Red text')
print(Back.BLUE + 'Blue background')
print(Style.RESET_ALL)
print('plain text again')

Here we imported modules to work with text and background. And just like before we output everything with built-in Python tools, we output everything to the console. The init function is worth paying attention to. If you forget to run it, it won’t support output on Windows 10. Only now we don’t have to write 33[44m, we just write Fore.BLUE, which is of course convenient. Style.RESET_ALL is to reset console colors to their original values. Result:

Output colored text to the console with colorama

Colored text with termcolor

This library gives the programmer a comprehensive toolkit for working with color text. Often termcolor is used in conjunction with colorama. Termcolor is used directly to write code; indeed, its syntax is more convenient and simpler. To install the termcolor library, run the pip install termcolor command in the console. Example:

from termcolor import colored, cprint
print(colored('Hi world!', 'red', attrs=['underline'])
print('Hi, I love you!')
cprint('output with cprint', 'green', 'on_blue')

Here we used the colored and cprint functions. The first one creates a line with the colors and effects you want to print. The second one produces immediate output to the console. The result:
Output colored text to the console with colorama

Conclusion

If we make a couple of functions for displaying colored error and warning messages in the console, you can make them without connecting the libraries. But if you include a library, the code becomes more readable. When choosing between colorama and termcolor libraries, I would choose colorama. Not only because of its greater popularity, but also because it supports the Windows 10 command line. Although cprint is a handy feature of termcolor.

Related Posts

LEAVE A COMMENT