How to print colored text in python

how to print colored text in python

This article will show different ways to how to print colored text in python. There are some python libraries and built-in methods to print the colored text in python.

The first question is why there are, by default, to print colored text in python because python is an interpreted language and can be run only using a terminal or command prompt in windows. So printing colored text without using other methods is difficult.

But solutions are many to print colored text and change text color in the python terminal.

So let’s get started with changing the color of the python text.

List of methods used how to change the text in python print statement

Now let’s start coding by trying each method one by one.

Method 1: The Python ANSI escape-sequence Method

In this method, we will use the python ANSI escape sequence method to change the text color in python.

But first, let’s learn about the ANSI escape sequence.

What is the ANSI escape sequence in Python?

The ANSI escape sequence in Python is a set of special characters that can use to modify the text output on a terminal. These characters start with the escape character “\x1b” (ASCII code 27) and are followed by a series of characters that specify the desired modification.

Some commonly used ANSI escape sequences in Python include

  • “\x1b[0m” – Resets all text formatting to default.
  • “\x1b[1m” – changes the text to bold.
  • “\x1b[2m” – changes the text to faint/dim.
  • “\x1b[3m” – changes the text to italic.
  • “\x1b[4m” – changes the text to underline.
  • “\x1b[31m” – changes the text color to red.
  • “\x1b[32m” – changes the text color to green.
  • “\x1b[33m” – changes the text color to yellow.
  • “\x1b[34m” – changes the text color to blue.
  • “\x1b[35m” – changes the text color to magenta.
  • “\x1b[36m” – changes the text color to cyan.
  • “\x1b[37m” – changes the text color to white.

To use these escape sequences in Python, you can simply add them to your print statement before the text you want to modify. For example, to print the word “Hello” in red, you can use the following code:

Note that some terminal emulators may not support all ANSI escape sequences, so it’s a good idea to test your code on different terminals to ensure compatibility.

In the terminals, two color codes are mostly used:

  • There are 16 colors available, with 8 for the background and 8 for the foreground. 
  • 256 different colors

The 16 colors option utilizes 8 foregrounds and 8 background colors. Refer to the color codes listed below for each foreground and background color.

Let’s see some examples of the ANSI method.

Example 1: How to print colored text in python using the 16 ANSI method.

#Print the colored text with the starting color codes
print('3[1;34;42m' + 'Welcome to PythonScholar ')


#Print the colored text with the starting and ending color codes
print('3[2;31;47m' + 'Some text here' + '3[0;0m')

Output:

Example 2: Print Rainbow colored text in python.

print("\x1b[31mR\x1b[33mA\x1b[32mI\x1b[36mN\x1b[34mB\x1b[35mO\x1b[31mW\x1b[0m")

Output:

Print Rainbow colored text in python

Example 3: Print blinking color text using python.

#Print the colored text with the starting color codes
print('3[5;34;45m' + 'Welcome to PythonScholar ')


#Print the colored text with the starting and ending color codes
print('3[6;31;43m' + 'Some text here'+ '3[0;0m')

Output:

Print blinking color text using python

So after seeing this example, we have printed many different types of colored text using python ANSI escape sequence in python.

Now let’s see the second method using the python Colorama package

Method 2: How to change the text using the python Colorama package.

The Colorama package is a Python module that allows you to add colored text and styling to your command-line interfaces easily. It works on Windows, Linux, and macOS and provides an easy-to-use interface for applying ANSI escape sequences to text.

To use Colorama, you first need to install it using pip:

pip install colorama

Once installed, you can use the package in your Python code as follows:

Example : How to print colored text in python using colorama

from colorama import Fore, Back, Style
print(Fore.RED + "This text is red!" + Fore.RESET)

In this example, we import the Fore, Back, and Style classes from colorama. These classes allow us to modify our output’s foreground color, background color, and text style, respectively.

We then use the Fore.RED class to set the foreground color of our text to red, and add the string “This text is red!” to our output. Finally, we use the Fore.RESET class to reset the foreground color to its default value.

Here are some more examples of how to use Colorama:

print(Back.YELLOW + Fore.BLACK + "Warning!" + Style.RESET_ALL)

The following code will display the text “Warning!” in black text color with a yellow background.

print(Fore.BLUE + "This text is underlined!" + Style.RESET_ALL + Style.BRIGHT + Back.CYAN + "PythonScholar" + Style.RESET_ALL)

This will print two separate strings with different formatting. The first string will be blue and underlined, and the second string will be bold with a cyan background.Overall, Colorama provides a simple and convenient way to add color and style to your command-line interfaces in Python.

Method 3: Change python text using Python colored package.

The Python colored package is a third-party Python module that provides a simple and easy-to-use interface for adding colored text to your command-line interfaces. Like Colorama, it uses ANSI escape sequences to modify the output of your text.

To use color, you first need to install it using pip:

pip install colored

Once installed, you can use the package in your Python code as follows:

Example : How to print colored text in python using colored

from colored import fg, bg, attr

print(fg('red') + "This text is red!" + attr('reset'))

In this example, we use the fg function to set the foreground color of our text to red, and add the string “This text is red!” to our output. We then use the attr function to reset the color to its default value.

Here are some more examples of how to use colored:

print(bg('yellow') + fg('black') + "Warning!" + attr('reset'))

This will print the word “Warning!” with a yellow background and black text color.

print(fg('blue') + attr('underline') + "This text is underlined!" + attr('reset') + attr('bold') + bg('cyan') + " PythonScholar" + attr('reset'))

This will print two separate strings with different formatting. The first string will be blue and underlined, and the second string will be bold with a cyan background.

Overall, colored provides a simple and convenient way to add color and style to your command-line interfaces in Python. However, note that it is a third-party package and may not be as widely used or supported as Colorama.

Method 4: Print colored output in python using the prompt_toolkit package.

The prompt_toolkit package is a Python module that provides a framework for building command-line interfaces with advanced features such as syntax highlighting, auto-completion, and mouse support. It is designed to be highly customizable and easy to use, making it a popular choice for building interactive command-line applications.

To use prompt_toolkit, you first need to install it using pip:

pip install prompt_toolkit

Once installed, you can use the package to create a command-line interface with the following steps:

Step 1: Import the necessary classes and functions from prompt_toolkit:

from prompt_toolkit import prompt, print_formatted_text
from prompt_toolkit.styles import Style
from prompt_toolkit.token import Token

Step 2: Define a style for your text using the Style class. You can use this to customize the colors and other formatting options for your output:

style = Style.from_dict({
    Token.Hello: 'bold #ff0066',
    Token.World: 'italic #00ff66',
})

In this example, we define a style with two tokens: Hello and World. The Hello token is set to bold and a bright pink color, while the World token is set to italic and a bright green color.

Step 3: Use the print_formatted_text function to print your text with the defined style:

text = [
    (Token.Hello, 'Hello'),
    (Token.World, 'world!')
]
print_formatted_text(text, style=style)

In this example, we define a list of tuples that represents our output text. Each tuple contains a token and a string that should be styled using that token. We then pass this list to the print_formatted_text function along with our defined style.

Step 4: Use the prompt function to get input from the user with the desired prompt text and optional arguments for auto-completion, history, and other features:

user_input = prompt('Enter your name: ', completer=None, history=None)

In this example, we use the prompt function to get input from the user with the prompt text “Enter your name: “. We also specify completer=None and history=None to disable auto-completion and history features, respectively.

Overall, prompt_toolkit provides a powerful and flexible framework for building advanced command-line interfaces in Python. It is well-documented and widely used, making it popular for building interactive CLI applications.

Method 5: Using Python termcolor package to print colored text in python

The termcolor package is a third-party Python module that provides an easy-to-use interface for adding colored output to your command-line interfaces. It uses ANSI escape sequences to modify the output of your text.

To use termcolor, you first need to install it using pip:

pip install termcolor

Once installed, you can use the package in your Python code as follows:

from termcolor import colored

print(colored('Hello, world!', 'red'))

In this example, we use the colored function to print the string “Hello, world!” with red color. The second argument to the colored function specifies the color of the text, which can be any of the following: grey, red, green, yellow, blue, magenta, cyan, or white.

Here are some more examples of how to use termcolor:

print(colored('Warning!', 'yellow', 'on_red'))

This will print the word “Warning!” with a yellow foreground color and a red background color.

print(colored('Success!', 'green', attrs=['bold', 'underline']))

This will print the word “Success!” with green color, bold and underline attributes.

Overall, termcolor provides a simple and convenient way to add color and style to your command-line interfaces in Python. However, note that it is a third-party package and may not be as widely used or supported as Colorama.

Method 6: Python simple_color package to print colored text in python.

simple_color is a Python package that provides an easy-to-use interface for adding colored output to your command-line interfaces.

 You can install it using pip: 

pip install simple_color

Once installed, you can use the package in your Python code as follows:

from simple_color import *

print(color("Hello, world!", Colors.RED))

In this example, we use the color function to print the string “Hello, world!” with red color. The second argument to the color function specifies the color of the text, which can be any of the following: RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, or WHITE.

Here are some more examples of how to use simple_color:

print(color("Warning!", Colors.YELLOW, bg=Colors.RED))

This will print the word “Warning!” with a yellow foreground color and a red background color.

print(color("Success!", Colors.GREEN, style=Styles.BOLD | Styles.UNDERLINE))

This will print the word “Success!” with green color, bold and underline attributes.

Overall, simple_color provides a simple and convenient way to add color and style to your command-line interfaces in Python.

FAQs

Can I print colored text in other ways besides ANSI escape sequences?

Yes, there are other ways to print colored text in Python using external libraries such as termcolor and colorama.

Can I combine ANSI escape sequences with other formatting options, like bold or italic?

Yes, you can combine ANSI escape sequences with other formatting options using the same syntax as for colored text.

Are ANSI escape sequences cross-platform?

ANSI escape sequences are supported on most Unix-based systems (including Linux and macOS), as well as on Windows 10 and later. However, some older versions of Windows may not support ANSI escape sequences.

Are there any limitations to using colored text in Python?

Yes, there are some limitations to using colored text in Python. Colored text may not display properly in certain terminals or operating systems, and some users may have difficulty reading text in certain colors. Additionally, if you are using colored text in a script that outputs to a file, the colors may not be preserved in the file.

What are some common use cases for colored text in Python?

Colored text can be useful for highlighting important information, differentiating between different types of output, or making output more visually appealing. Some common use cases include printing error messages in red, success messages in green, and warnings in yellow.

Related Articles

How to make a Hangman Game in Python – [GUI Source Code]

How to Make a Rule based Chatbot in Python using Flask

Pig Game in Python

Convert Celsius to Fahrenheit in Python – [With Chart]

Dice Rolling Simulator in Python – [GUI Source Code]

How to Create Mad Libs game in Python