How To Change Text Color In Python

Changing the text color is a common requirement when working with text-based programs.

One of the simplest and most popular ways to achieve this in Python is by using the Colorama module, which allows you to easily customize the color and style of printed text in your Python console applications. In this tutorial, we will learn how to change text color in Python using the Colorama module.

Firstly, you need to install the Colorama library if you don’t have it installed already. To do this, you can use the following pip command:

Step 1: Import the Colorama module

Before using Colorama to change the text color, you must first import the required classes and functions from the Colorama module. Add the following lines to your Python script:

This imports the init, Fore, and Style classes from the Colorama module.

Step 2: Initialize Colorama

You need to initialize the Colorama library by calling the init() function. This function ensures that your printed text is displayed correctly on different platforms (e.g. Windows, Linux, and macOS). Add the following line to your Python script:

Step 3: Change the text color

Now that you have imported and initialized the Colorama library, you can change the color of your printed text by prefixing your print statement with the desired color code from the Fore class.

For example, to print text in the red color you can use the following code:

Similarly, you can use other color codes, such as Fore.GREEN, Fore.BLUE, Fore.YELLOW, Fore.MAGENTA, Fore.CYAN, and Fore.WHITE.

Step 4: Reset the text color (optional)

Whenever you change the text color using Colorama, it will retain the changed color for subsequent print statements. To reset the text color back to the default, you can use the Style.RESET_ALL attribute, like so:

Full Code

Now that you know the steps, here’s the complete code for changing text color using the Colorama library in Python:

Output

The output of the above code will be:

Conclusion

In this tutorial, we learned how to change the text color in Python using the Colorama library. We covered how to install and import the Colorama module, initialize it, and change the text color using the Fore class, and reset the text color using the Style.RESET_ALL attribute.

With these skills, you can now easily customize the color and style of your Python console applications to provide a more engaging and visually appealing user experience.