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 = '33[95m'
OKBLUE = '33[94m'
OKCYAN = '33[96m'
OKGREEN = '33[92m'
WARNING = '33[93m'
FAIL = '33[91m'
ENDC = '33[0m'
BOLD = '33[1m'
UNDERLINE = '33[4m'
print(f"{bcolors.WARNING}Warning{bcolors.ENDC}")
to define the bcolors
class with some escape codes for various styles to apply.
33[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.