How to add colour to text Python?
There are multiple ways supported by python in which color can be added ot 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.
- Declare class ANSI
- Declare functions in this class to perform a special text formatting task
- Call the required function using the class object
- 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
Table 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
- Import module
- Use colored() function to add color to the text
- Print colored text
colored(text, color, attribute_array)
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
- Import module
- Call Fore with required color
- Pass the text to be colored.
- Print result
In colorama, the implementation is different in comparison to ANSI escape and Colored.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course