Open In App

How to add colour to text Python?

There are multiple ways supported by python in which color can be added to text. This article discusses all with proper examples to help you understand better.

Method 1: Using ANSI ESCAPE CODE

ANSI escape sequence is a sequence of ASCII characters, the first two of which are the ASCII “Escape” character 27 (1Bh) and the left-bracket character ” [ ” (5Bh). The character or characters following the escape and left-bracket characters specify an alphanumeric code that controls a keyboard or display function.



To add color and style to text, you should create a class called ANSI, and inside this class, declare the configurations about the text and color with code ANSI.

Approach



Functions Used:

Example:




class ANSI():
    def background(code):
        return "\33[{code}m".format(code=code)
 
    def style_text(code):
        return "\33[{code}m".format(code=code)
 
    def color_text(code):
        return "\33[{code}m".format(code=code)
 
 
example_ansi = ANSI.background(
    97) + ANSI.color_text(35) + ANSI.style_text(4) + " TESTE ANSI ESCAPE CODE"
print(example_ansi)

Table ANSI Escape Code

TABLE ANSI ESCAPE CODE

Output:

Example Ansi Escape Code

Method 2:  Using Colored

To use this module it first needs to be installed using pip since it doesn’t come inbuilt with python. 
 

pip install termcolor

Approach

Syntax:

colored(text, color, attribute_array)

Example:




from termcolor import colored
 
text = colored('Hello, World!', 'red', attrs=['reverse', 'blink'])
 
print(text)

Output:

Method 3: Using Coloroma

It makes ANSI escape character sequences for producing colored terminal text and cursor positioning work under MS Windows.

It needs to be installed manually using pip

pip install colorama

Approach

Syntax:

Fore.(color_of_text, text)

In colorama, the implementation is different in comparison to ANSI escape and Colored.

Example:




from colorama import Fore, Back, Style
 
print(Fore.RED + 'some red text')

Output:


Article Tags :