To print a colored text in python console, there are several ways such as
These Python libraries are used to color and format the text accordingly. Let's see some examples.
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
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
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