Friday, December 27, 2024
Google search engine
HomeLanguagesHow to add colour to text Python?

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

  • Declare class ANSI
  • Declare functions in this class to perform a special text formatting task
  • Call the required function using the class object

Functions Used:

  • background: allows background formatting. Accepts ANSI codes between 40 and 47, 100 and 107
  • style_text: corresponds to formatting the style of the text. Accepts ANSI code between 0 and 8
  • color_text:  Corresponds to the text of the color. Accepts ANSI code between 30 and 37, 90 and 97

Example:

Python3




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

  • Import module
  • Use colored() function to add color to the text
  • Print colored text
     

Syntax:

colored(text, color, attribute_array)

Example:

Python3




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

  • Import module
  • Call Fore with required color
  • Pass the text to be colored.
  • Print result

Syntax:

Fore.(color_of_text, text)

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

Example:

Python




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


Output:

RELATED ARTICLES

Most Popular

Recent Comments