Categories
Python Answers

How to print colored text to the terminal with Python?

Spread the love

Sometimes, we want to print colored text to the terminal with Python.

In this article, we’ll look at how to print colored text to the terminal with Python.

How to print colored text to the terminal with Python?

To print colored text to the terminal with Python, we can surround the string we’re print with the escape code for the color to print.

For instance, we write:

class bcolors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKCYAN = '\033[96m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'


print(f"{bcolors.WARNING}Warning{bcolors.ENDC}")

to define the bcolors class with some escape codes for various styles to apply.

\033[0m lets us stop applying the given style from this point onward.

Therefore, the text we print should have a brownish color.

Conclusion

To print colored text to the terminal with Python, we can surround the string we’re print with the escape code for the color to print.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *