How to change text colour in the console?

When printing to the console, how would I change the colour of the text? Is there something that works for all languages?

3 Likes

You can use 8 bit ANSI escape codes, which should work for all languages in Replit.

The ANSI code follows this format:
\033[38;5;<COLOUR>m for text colour
\033[48;5;<COLOUR>m for background colour

You replace <COLOUR> with a colour code, shown below:


You insert each code at the start of the string you want to colour.

For example in Python:

# pink text
print("\033[38;5;201mHello World!")

Or in C++:

// light green background
std::cout << "\033[48;5;154mHello World!\n";
3 Likes

There are also some nice libraries out there on npm, pip, etc that allow easy styling of terminals.

Here are some sample code for colorama I use, adapted from java - How to print color in console using System.out.println? - Stack Overflow

Java:
System.out.println("\033[1;31mThis text is a different color.\033[0m");

Python example code:

from colorama import Fore, Back, Style
result = Fore.WHITE + Style.BRIGHT + Back.GREEN
result += "This text is a different color."
result += Style.RESET_ALL
print(result)
2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.