How to Print Colored Text in Python

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'.

Using ‘colorama’ Library for Printing Colored Text

The 'colorama' library is a popular choice for cross-platform colored terminal text in Python applications.

Using 'colorama' Library for Printing Colored Text

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'.

Using the 'termcolor' Library for Colored Text

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

See Also

1 thought on “How to Print Colored Text in Python”

Leave a Comment