How to Print Colored Text in Python?

5/5 - (2 votes)
  • Summary: To print colored text in Python, you can use:
    • The simple_color package,
    • The '\033[1m' ANSI escape-sequence,
    • The termcolor module,
    • The coloroma package,
    • The colored library,
    • The prompt_toolkit package.

A simple, no-library way to print bolded text in Python is to enclose a given string s in the special escape sequence like so: print("\033[38;5;4m").

We’ll discuss the most Pythonic solution in Method 2 in this article.


You can change your text to bold, italic, and underlined in Python. Not only can you play around with the style of your code but also change its color with the help of specific packages and modules in Python.

Interesting! Isn’t it?

There are different ways of doing this. By the end of this tutorial, you will be equipped with all the instruments to play around with the style of your code.

Related Tutorials:

So, without further delay, let the games begin!

📹Video Walkthrough

How to Print Colored Text in Python

Method 1: Using The simple-color Package

Python provides a spectacular package by the name simple-color that enables us to display colored text in the terminal.

  • The simple_colors package includes colors like blue, black, green, magenta, red, yellow, and cyan.
  • You can also format your text in various styles like bold, dim, italic, bright, underlined, reverse and blink that are included in the package.

Since the simple-color package isn’t a part of Python’s standard library, you need to install it before utilizing it. To install the simple_color package, copy the following code on your terminal:

pip install simple-colors

or,

python -m pip install simple-colors

After you have successfully installed the module, you can follow the syntax given in the example below to customize/style your code.

Example: The following example demonstrates how you can add color, format, and make the text bold or even underline it using the simple_colors module.

import simple_colors

# colored text
print('Normal:', simple_colors.blue('Welcome Finxter!'))
# BOLD and colored text
print('BOLD: ', simple_colors.green('Welcome Finxter!', 'bold'))
# BOLD and Underlined and colored text
print('BOLD and Underlined: ', simple_colors.red('Welcome Finxter!', ['bold', 'underlined']))

Output:

colored_text_python_img1

Hurrah! That look’s amazing.

Explanation:

  • To display a colored text, you have to call the specific color function from the simple-colors library and pass the text within this function. For example, the first print statement displays a blue-colored text with the help of the simple_colors.blue('text') function. Similarly, when you call the simple_colors.green('text') method, it will generate a green text.
  • To add styles along with colors to the text, we used the specific color method and passed the type of formatting (bold, italic, underline, etc.) as an argument to the colour function. To add more than one style of formatting to your text, you can simply pass the formatting styles as an argument to the function by packing them within a list.

Method 2: Using The ANSI Escape Sequence

The Most Pythonic way to print colored text in Python is to enclose a given string s in the special escape sequence like: print("\033[38;5;4m").

Here’s a minimal example:

s = "abc"
print("Uncoloured text: ", s)
colored_s = "\033[38;5;4m" + s
print("Coloured text: ", colored_s)

You can try this yourself in our interactive Jupyter notebook:

🧩 Interactive: Try it yourself in Google Colab

Let’s dive into some further explanations to see why this works next.

Some terminals support the capacity to pass in unique escape sequences to modify the tone, color, and appearance of the content being printed. These escape sequences are called ANSI escape sequences that got named after the ANSI standard that indicates their use. 

Thus, you can utilize the built-in ANSI escape sequence to create colored content. Here’s a breakdown of the ANSI sequences that you can use within your code:

  • The placeholder determines whether the color has to be applied to the text itself or to the text background-
    • 38;5; is for the text and
    • 48;5; is for the background.
  • This is followed by the color code ranging from 0 to 255.

Example: The following example demonstrates how you can use Escape-Sequences to print colored, underlined, and bold text simultaneously.

print("\033[31;1;4mThis line gets printed in bold, underlined, and red color.\033[0m")

Output:

💡 NOTE: The code '\033[0m' is used to end the bold text format. If you forget to add the ANSI code sequence to enclose the specific line of code, the following statements will also be printed in bold format.

Method 3: Using termcolor Module

In Python, termcolor is a module utilized for the ANSII color formatting.

The module comes with various properties for various terminals and certain text formatting properties. It also includes various text colors like blue, red, and green and text highlights like on-magenta, on-cyan, and on-white.

💡 Note: termcolor module isn’t a part of Python’s standard library. Thus, you need to install it before utilizing it. To install the termcolor module, copy the following code on your terminal:

pip install termcolor

After installing the module, let’s visualize how you can use it to print colored text.

Example:

from termcolor import colored
text = colored('Welcome FINXTER!', 'blue', attrs=['bold'])
print(text)

Method 4: Using The Colorama Package

ANSI escape character sequences have long been used to produce colored terminal text and cursor positioning on Unix and Macs.

Colorama makes this work on Windows, too, by wrapping stdout, stripping ANSI sequences it finds (which would appear as gobbledygook in the output), and converting them into the appropriate win32 calls to modify the state of the terminal. On other platforms, Colorama does nothing.

  • Note:
    • On other platforms, Colorama does nothing. In Windows, calling init() will shift the ANSI escape sequence of any content sent to stdout or stderr and replace it with Win32 calls.
    • To quit utilizing Colorama before your program exits, call deinit(). It will restore the stdout and stderr to their original value.

Source: https://pypi.org/project/colorama/

Since coloroma is not a part of Python’s standard library, you have to install it using the following command in your terminal before you can use it.

pip install colorama

Let’s have a look at an example to understand how we can use the Colorama module to print bold text in Python.

Example 1:

from colorama import Fore, Style

print(Style.BRIGHT + 'Bold text')
print(Fore.BLUE + 'Printing blue colored text')
print(Style.RESET_ALL)
print('This line has no effect of coloroma')

Output:

Example 2: Using coloroma package along with the termcolor module.

from colorama import init
from termcolor import colored

init()
print(colored('Hello and Welcome to Finxter!', 'blue', attrs=['bold']))

Output:

Method 5: Using the colored Module

colored is a very simple Python library used for coloring and formatting text in terminal. Since it is not a built-in module, you first have to install it using pip: pip install colored

Usage Example:

from colored import fore, back, style
print (fore.RED + back.YELLOW + style.BOLD + "Hello FINXTER!!!" + style.RESET)

Output:

Method 6: Create an Html Object 

Prompt_toolkit includes a print_formatted_text() function that is compatible (as much as possible) with the built-in print() function. It also supports colors and formatting.

HTML can be utilized to demonstrate that a string contains HTML based formatting. Thus, the HTML object recognizes the essential tags for bold, italic and underline: <b>, <i> and <u>.

Example 1:

from prompt_toolkit import print_formatted_text, HTML

print_formatted_text(HTML('<b>This text is bold</b>'))
print_formatted_text(HTML('<i>This text is italic</i>'))
print_formatted_text(HTML('<u>This text is underlined</u>'))

Output:

Example 2:

As all the HTML tags are mapped to classes from a style sheet, you can also appoint a style for a custom tag.

from prompt_toolkit import print_formatted_text, HTML
from prompt_toolkit.styles import Style

sty = Style.from_dict({
       'y': '#44ff00 bold',
})

print_formatted_text(HTML('<red> Hello and welcome to <u>Finxter!</u> </red>'), style=sty)

Output:

Conclusion

We have finally conquered the art of printing bold texts in Python. Not only did we learn how to print bold texts, but we also learned how to style the code using colors and other formatting styles like underline and italics. I hope this article helped you.


Please stay tuned and subscribe for more interesting articles!

The Complete Guide to PyCharm
  • Do you want to master the most popular Python IDE fast?
  • This course will take you from beginner to expert in PyCharm in ~90 minutes.
  • For any software developer, it is crucial to master the IDE well, to write, test and debug high-quality code with little effort.

Join the PyCharm Masterclass now, and master PyCharm by tomorrow!