How to Print Colored Text in Python. Printing colored text in Python can enhance the readability of output in console applications, making it easier to convey information through different colors. This can be particularly useful in debugging, distinguishing log levels, or simply making a console output more visually appealing. In this tutorial, we will explore various methods to print colored text in Python using different libraries such as 'colorama
‘ and 'termcolor'.
Table of Contents
Using ‘colorama’ Library for Printing Colored Text
The 'colorama'
library is a popular choice for cross-platform colored terminal text in Python applications.
from colorama import init, Fore, Back, Style
init(autoreset=True)
print(Fore.RED + "This is red text")
print(Back.GREEN + "This is green background")
print(Style.DIM + "This text is dim")
print(Fore.BLUE + Back.YELLOW + Style.BRIGHT + "Blue text on yellow background with bright style")
In the above code-
- We need to import
'colorama'
in our Python script. 'init()'
initializes'colorama'
and the ‘autoreset=True’ argument automatically resets the colored to the default after every print statement.- ‘Fore’, ‘Back’, and ‘Style’ are modules for setting the foreground (text) color, background color, and style (like bold, dim, bright, etc), respectively.
- By using ‘Fore’, ‘Back’, and ‘Style’ different texts are printed.
Using the ‘termcolor’ Library for Colored Text
Another library, 'termcolor'
, is also widely used for printing colored text but is more straightforward compared to 'colorama'
.
from termcolor import colored
print(colored('Hello, World', 'yellow'))
print(colored('Warning!', 'red', attrs=['reverse', 'blink']))
print(colored('This is underline text', 'blue','on_white', attrs=['underline']))
Note: You need to install 'termcolor'
library “`pip install termcolor
“`
In the above code-
- First, we imported
'colored'
function from'termcolor'
library. - After that, we use the
'colored'
function to apply colors and attributes- The first argument is the text string.
- The second argument is the text color.
- The third optional argument is the background color.
'attrs'
is a list of attributes like'bold', `'underline'
`, etc
By using libraries like 'colorama'
and 'termcolor',
we can easily add color text to our Python application, enhancing the user interface and improving readability. each library has its advantages. Choose the one that best fits your project’s needs and enhances your console output.
Happy Coding & Learning
1 thought on “How to Print Colored Text in Python”