×

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

Applications of Python

Top 10 Applications of Python in 2020- 2021 Python language is famous for its general-purpose nature, which enables developers to use it in every field of development. Python can be found...

6 minutes read.

Compound Interest GUI Calculator using Tkinter in Python

GUI: One of the most significant factors that increased the usability of computer and digital technologies for common, less tech-savvy users is likely the development and widespread adoption of GUIs. GUIs...

6 minutes read.

How to uninstall python

To un-install Python, we need to follow different procedures in different operating systems. In this article, we will discuss the un-installation process of Python in Windows, Mac, and Linux operating...

4 minutes read.

Arithmetic Expressions in Python

What is Python Expression? Expressions are collections of operands and operators. Python expressions are translated by the Python interpreter into some value or outcome. In Python, an expression is made up...

13 minutes read.

How to Take Input in Python

How To Take Input In Python Python has various in-built functions that help in code redundancy. Let's discuss the usage of some functions- ascii() – it returns a readable representation of objects.format()...

4 minutes read.

ModuleNotFoundError No module named 'mysql' in Python

mysql module not found is an error that occurs in python. It appears like ModuleNotError: No module named 'mysql.' This error occurs when you forget to install a module called...

3 minutes read.

Python Maurer Rose and Rhodonea Curves

In this tutorial, in Python we will make a Maurer Rose example and Rhodonea Curve example. Before we continue to see what precisely is maurer rose or a rhodonea bend...

10 minutes read.

Python if statement

Python if statement Decision making is an essential feature of any programming languages. Condition checking is the strength of decision making. Python provides many decision-making statements, such as: If statementIf-else statementelif statement if statement The if statement is...

2 minutes read.

Python Uses

Python has advanced in recent years to rank among the programming languages that are most often used globally. It is utilized in everything, including machine learning, software testing, and website...

4 minutes read.

Python Coroutine

Introduction In Python, Coroutines are defined as the special type of function that freely allows control to its caller without losing the state. Coroutines and generates are similar but coroutines consist...

3 minutes read.

Python Set update() method

Python Set update() method The set.update() method in Python updates the current set, by adding items from another set. If an element is common in both the sets, only one appearance of this item...

1 minute read.

Spark and Python for big data with pyspark github

Pyspark: Apache Spark is a computational engine that handles large data sets using parallel and batch processing. Apache Spark is an open-source, distributed computing framework and collection of libraries for real-time,...

3 minutes read.

Python BytesIO

Python Programming Language 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...

3 minutes read.

Yield vs Return in Python

In this article, you will learn about " Yield " and " Return " in Python. You will also understand the difference between " Yield " and " Return "...

6 minutes read.

Assertion Errors and Attribute Errors in Python

Assertion Error in Python In Python, the assert condition is used to continue the execution if the given statement displays true. If the assert statement displays false, it raises Assertion Error...

3 minutes read.

Python Ways to find nth occurrence of substring in a string

Introduction In Python, a string is a collection of characters that can be employed to conduct additional operations. In Python, a substring is a group of characters that are a part...

4 minutes read.

Colors in Python

Adding colour to your visualisations will help them come to life. Even if you know the colours you want to use, picking good ones and putting them into practise might...

4 minutes read.

Python Dictionary pop() method

Python Dictionary pop() method The dictionary.pop() method in removes the specified item and returns an element from a dictionary having the given key. Syntax dictionary.pop(key[, default]) Parameter key – This argument signifies the key which is to...

2 minutes read.

Python Word Tokenizer

Python Overview Python is an Object-Oriented high-level language. Python is designed to be highly beginner-friendly. Python has an English-like syntax, which is very easy to read. Python is an interpreted language...

4 minutes read.

How to Install Tweepy in Python

In this article, we will learn or understand how to install Tweepy in Python and what Tweepy is. Firstly, let’s understand What Tweepy is. As we all know, one of the...

3 minutes read.