Skip to content

[Python] print colorful string in terminal

Last Updated on 2021-06-18 by Clay

When we using Python to develop some program, sometimes we may want to print some colorful string in our terminal.

It's beautiful and we can quickly see the different text blocks printed.

Today I want to note a famous Python package: "colorama". It can help us to display our text colorful and show them on terminal. We just need to add some instruction in Python "print()" function.

Their PyPI document is very clear, maybe you can refer the end of the article.


How to use "colorama"

If this is the first time using this package, we need to install it with following instructions (or installation methods provided by IDE):

pip3 install colorama

The rendering of text is divided into "text color" and "background color". You can try more and more combinations.

The colors provided by "colorama" are as follows:

Fore: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, RESET.
Back: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, RESET.

"Fore" is text color, "Back" is background color.

So let's write a test script:

from colorama import init, Fore, Back

init(autoreset=True)
print("This is a test...")
print(Fore.RED + "Hello")
print(Fore.YELLOW + "World!")
print(Fore.BLACK + Back.WHITE + "Good day!")

Output:

It's good to show on my terminal screen, and my IDE PyCharm is not bad, too.

But the "Good day!" string have some problem to show, you can see the text color is not black.


Postscript

My impression is: this package is really awesome! in fact, last night I started using some famous machine learning framework and different models in Python to experiments with my task, I printed more and more model structures, activation functions, evaluation scores......and in the process, I always printed "=" to separate different experiments.

It's all very messy.

Honestly, "colorama" saved me (and my eyes). Now, with a glance, I can see which part is which model, and I have highlighted the important statements!

This package is really pretty good!


References

Leave a ReplyCancel reply

Exit mobile version