How to Change Text Color in Python
Satyajit Mohapatra
Data Scientist|BigData | Spark| Hadoop|AWS| Azure| GCP | CI/CD| Artificial Intelligence | Speaker | Data Science | Tech - Love to Spread Smile ?? #Happytohelp | Content writer | Blogger |
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:
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:
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:
This will look like in the following image:
Black is not showing, as the terminal's background color is black as well, here is with a different background color:
Let's now use background colors:
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:
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.
Data Scientist | Specializing in ML, Stats & AI | Proficient in LLM & OpenAI
3 年Thanks for sharing ??