How to Change Text Color in Python

How to Change Text Color in Python

Printing to the console in different colors is pretty handy and quite practical, from building fancy scanning scripts to distinguishing different log message types (debug, info, or critical, etc.) in your programs. In this tutorial, you will learn how you can print colored text in Python using colorama library.

We'll be using colorama, let's first install it:

$ pip install colorama

Next, open up a new Python file, and write the following:

No alt text provided for this image

First, we call the init() function, which is necessary on Windows environment for colorama to function properly, it does nothing on other platforms, so you can remove it.

Second, we define all the available foreground colors in FORES list, and background colors in BACKS list, we also define BRIGHTNESS list for different brightness setting.

Next, let's make a function that wraps the regular Python's print() function, but with the ability to set color and brightness:

No alt text provided for this image

We simply use print() inside, but prepending the text with brightness and color codes, and appending Style.RESET_ALL in the end to reset to default color and brightness each time we use the function.

We also pass **kwargs so we can use other print() function's keyword arguments, such as end and sep.

Now that we have our function, let's use all foreground colors and print the same text with different colors and each with different brightness:

No alt text provided for this image

This will look like in the following image:

No alt text provided for this image

Black is not showing, as the terminal's background color is black as well, here is with a different background color:

No alt text provided for this image

Let's now use background colors:

No alt text provided for this image

You can change the background and the foreground color in the same time, that's why we're iterating over foreground colors too, here's how it'll look:

No alt text provided for this image

Conclusion :

That's it! Now you know all the available foreground and background colors as well as brightness values in colorama library in Python. I hope this was helpful for you to quickly grasp information and copying code for your projects.


Poulami Bakshi

Data Scientist | Specializing in ML, Stats & AI | Proficient in LLM & OpenAI

3 年

Thanks for sharing ??

要查看或添加评论,请登录

社区洞察

其他会员也浏览了