How to Display Colored Text in Python
To print a colored text in python console, there are several ways such as
- termcolor library
- colorama library
- ANSI Code
These Python libraries are used to color and format the text accordingly. Let's see some examples.
Example: Print colored text using termcolor library in Python
from termcolor import colored
# Text
message = "Welcome to javaexercise.com"
# Set color to text
text = colored(message, 'green')
# Display colored text
print(text)
Output:
Welcome to javaexercise.com
Example: Print colored text using colorama library in Python
from colorama import Fore
# Text
message = "Welcome to javaexercise.com"
# Set color to text
text = Fore.RED + message
# Display colored text
print(text)
Output:
Welcome to javaexercise.com
Example: Print colored text using ANSI Code in Python
We can collectively use the ANSI code in a class and then call them accordingly.
# Text
message = "Welcome to javaexercise.com"
# Set color to text
class style():
BLACK = '\033[30m'
RED = '\033[31m'
GREEN = '\033[32m'
YELLOW = '\033[33m'
BLUE = '\033[34m'
MAGENTA = '\033[35m'
CYAN = '\033[36m'
WHITE = '\033[37m'
UNDERLINE = '\033[4m'
RESET = '\033[0m'
text = style.RED + message
# Display colored text
print(text)
Output:
Welcome to javaexercise.com