×

How To Print Colored Text in Python

Changing the colour of certain parts of a string when printing the output of a Python programme to the terminal may make it easier to read. We can approach this in a variety of ways and use packages to make things easier, as we will see in this tutorial.

Using ANSI Escape Sequences

The most basic way to print coloured text from a Python programme is to use ANSI escape sequences. To accomplish this, we will create a class with properties for applying different colours to text. Let's create a file called colors.py that contains a colours class, import it into the programme, and then use it on a f string.

The colors.py would look like this:

class bcolors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKGREEN = '\033[90m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'

We can import the bcolors class from colors.py using the following statements.

from colors import bcolors
return f'Successfully downloaded {bcolors.OKGREEN}{file.title}{bcolors.ENDC} to {formt}'

Each ANSI character escape sequence, as we can see, takes the form 033[XXXm. The text style is indicated by the part following the [(square bracket). Numbers 90-96 offer a variety of text colours. Here are some examples:

NumberColor
90 grey
91 red
92green
93yellow
94 blue
95pink
96turquoises

Changing the Background Color of Text

To change the background colour of text, use the ANSI escape sequence character numbers 100-107. Let's go ahead and add some background colours to the bcolors class we just created.

Colors.py should now look like this:

class bcolors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'
    # Background colors:
    GREYBG = '\033[100m'
    REDBG = '\033[101m'
    GREENBG = '\033[102m'
    YELLOWBG = '\033[103m'
    BLUEBG = '\033[104m'
    PINKBG = '\033[105m'
    CYANBG = '\033[106m'

Let us see how this will work.

return f'Successfully downloaded {bcolors.GREENBG}{file.title}{bcolors.ENDC} to {formt}'

Here are all the available background colors and their corresponding ANSI number:

NumberColor
100 gray
101 red
102green
103yellow
104 blue
105pink
106turquoise

All the Available Font Effects

For reference here are all the available font effect codes to change the style of text in the terminal:

Number(s)Effect
0Reset / Normal
1Bold or increased intensity
2Faint (decreased intensity)
3Italic
4Underline
5Slow Blink
6Rapid Blink
7[[reverse video]]
8Conceal
9Crossed-out
10Primary(default) font
11–19Alternate font
20Fraktur
21Bold off or Double Underline
22Normal color or intensity
23Not italic, not Fraktur
24Underline off
25Blink off
27Inverse off
28Reveal
29Not crossed out
30–37Set foreground color
38Set foreground color
39Default foreground color
40–47Set background color
48Set background color
49Default background color
51Framed
52Encircled
53Overlined
54Not framed or encircled
55Not overlined
60ideogram underline
61ideogram double underline
62ideogram overline
63ideogram double overline
64ideogram stress marking
65ideogram attributes off
90–97Set bright foreground color
100–107Set bright background color

The colorama Package

Install the colorama package if you'd rather use a package to change the print colours in Python. To install it, enter the following command into your terminal:

pip install colorama

Then, in your programme, import the foreground, background, and style classes:

from colorama import Fore, Back, Style

To make some text red, use Fore.RED, and to make the rest of the text normal, use Style. RESET ALL

return f'Successfully downloaded {Fore.RED}{file.title}{Style.RESET_ALL} to {formt}'

Here are all the formatters available in colorama:

Fore - BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, RESET.
Back - BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, RESET.
Style - DIM, NORMAL, BRIGHT, RESET_ALL

Now you can easily print colored text in the python terminal!

Keep Learning!


Related Topics

How to Make an App with Python

In this age of mobiles, rapid mobile application development has got a lot of traction. Moreover, app developers are high in demand because of the increase in digitization. Generally, Python is...

4 minutes read.

Import Function in Python

In Python programming language, the import keyword plays an important role in the whole code because it makes one module make available in another module. Import is used to structure...

3 minutes read.

Polymorphism in Python

What is polymorphism and why is it important? Polymorphism's literal definition is the state of occurring in diverse shapes or forms. When it comes to programming, the idea of polymorphism is crucial....

3 minutes read.

What Does the Percent Sign (%) Mean in Python?

In python, the percent sign is called modulo operator " %, " which returns the rest of partitioning the left-hand operand by the right-hand operand. Example: value1 = 8 value2 = 2 remainder =...

4 minutes read.

Iterators in Python

Introduction In Python, an iterator is defined as an object that enables traversing through all the values of a collection. It contains the countable number of values. The iterator is utilized to...

4 minutes read.

Image to Text in python

Processing out information from an image is a very big task in all the fields of work such as in development and business sector. The process of converting an electronical...

3 minutes read.

Python Memory Management

In order to manage memory, Python uses a private heap that contains all of its data structures and objects. The Python memory manager is responsible for the internal management of...

11 minutes read.

Python program to sort the array element into ascending order

Python program to sort the array element into ascending order In this example, we'll see how to sort the array elements in ascending order using a Python program. Sorting is a...

2 minutes read.

Python program to count and display vowels in a string

Python program to count and display vowels in a string This python program counts the vowels in a string and displays them on the screen. We can do this in several...

2 minutes read.

XXhash Python

Python: Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It is said...

6 minutes read.

Speech Recognition Module in Python

Speech Module in Python: Converting text to speech, known as Speech Synthesis, this process is the computer-generated recreation of human speech. This module converts the human language text into human-like...

8 minutes read.

Python | a += b is not always a = a + b

a += b in Python doesn't always behave the same way as a = a + b; the same operands can produce different outcomes depending on the circumstances. But we...

3 minutes read.

Python Slice from Last Occurrence of K

Introduction We already know that in Python, cutting produces a sub-string out of a string. The variables start, stop, and step are used to set the slicing range. When dealing on...

3 minutes read.

Data Structures and Algorithms using Python | Part 2

Files: A file is a location or information stored in computer storage devices. File handling is essential when the information or the data is to be held permanently. When we try to...

20 minutes read.

Abstraction in Python

What is meant by abstraction generally? A very general notion of a thing or work is known as abstract. To be more precise, the process of having a brief idea but...

4 minutes read.

Python Graph

Python Graph: In Computer Science and Mathematics, a Graph is a pictorial representation of a group of objects or elements where some elements are connected using the links. A graph...

5 minutes read.

How to Write a Configuration file in Python

This article will discuss How to write a configuration file in python, why we need config files in Python, the format of the configuration file, file extensions, and how to...

11 minutes read.

Unicode to String in Python

Python Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

How to Declare a Variable in Python?

The concept of constants and variables is something that we are studying right from our primary classes. We know that constants are the fixed values whereas variables are those whose...

4 minutes read.

Python | Read csv using pandas.read_csv()

Python is an excellent language for performing information analysis, owing to the fantastic biological system of information-driven python packages. Pandas is one of those packages that make taking in and...

4 minutes read.