How to print colored text to the terminal?

StackOverflow

How can I output colored text to the terminal in Python?

Answer rating: 2265

This somewhat depends on what platform you are on. The most common way to do this is by printing ANSI escape sequences. For a simple example, here"s some Python code from the Blender build scripts:

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"

To use code like this, you can do something like:

print(bcolors.WARNING + "Warning: No active frommets remain. Continue?" + bcolors.ENDC)

Or, with Python 3.6+:

print(f"{bcolors.WARNING}Warning: No active frommets remain. Continue?{bcolors.ENDC}")

This will work on unixes including OS X, Linux and Windows (provided you use ANSICON, or in Windows 10 provided you enable VT100 emulation). There are ANSI codes for setting the color, moving the cursor, and more.

If you are going to get complicated with this (and it sounds like you are if you are writing a game), you should look into the "curses" module, which handles a lot of the complicated parts of this for you. The Python Curses HowTO is a good introduction.

If you are not using extended ASCII (i.e., not on a PC), you are stuck with the ASCII characters below 127, and "#" or "@" is probably your best bet for a block. If you can ensure your terminal is using a IBM extended ASCII character set, you have many more options. Characters 176, 177, 178 and 219 are the "block characters".

Some modern text-based programs, such as "Dwarf Fortress", emulate text mode in a graphical mode, and use images of the classic PC font. You can find some of these bitmaps that you can use on the Dwarf Fortress Wiki see (user-made tilesets).

The Text Mode Demo Contest has more resources for doing graphics in text mode.

Answer rating: 968

There is also the Python termcolor module. Usage is pretty simple:

from termcolor import colored

print colored("hello", "red"), colored("world", "green")

Or in Python 3:

print(colored("hello", "red"), colored("world", "green"))

It may not be sophisticated enough, however, for game programming and the "colored blocks" that you want to do...

Answer rating: 855

The answer is Colorama for all cross-platform coloring in Python.

It supports Python 3.5+ as well as Python 2.7.

And as of January 2021 it is maintained.

Example screenshot: example screenshot

Answer rating: 523

Print a string that starts a color/style, then the string, and then end the color/style change with "x1b[0m":

print("x1b[6;30;42m" + "Success!" + "x1b[0m")

Success with green background example

Get a table of format options for shell text with the following code:

def print_format_table():
    """
    prints table of formatted text format options
    """
    for style in range(8):
        for fg in range(30,38):
            s1 = ""
            for bg in range(40,48):
                format = ";".join([str(style), str(fg), str(bg)])
                s1 += "x1b[%sm %s x1b[0m" % (format, format)
            print(s1)
        print("
")

print_format_table()

Light-on-dark example (complete)

Enter image description here

Dark-on-light example (partial)

Top part of output

Answer rating: 254

Define a string that starts a color and a string that ends the color. Then print your text with the start string at the front and the end string at the end.

CRED = "33[91m"
CEND = "33[0m"
print(CRED + "Error, does not compute!" + CEND)

This produces the following in Bash, in urxvt with a Zenburn-style color scheme:

Output colors

Through experimentation, we can get more colors:

Color matrix

Note: 33[5m and 33[6m are blinking.

This way we can create a full color collection:

CEND      = "33[0m"
CBOLD     = "33[1m"
CITALIC   = "33[3m"
CURL      = "33[4m"
CBLINK    = "33[5m"
CBLINK2   = "33[6m"
CSELECTED = "33[7m"

CBLACK  = "33[30m"
CRED    = "33[31m"
CGREEN  = "33[32m"
CYELLOW = "33[33m"
CBLUE   = "33[34m"
CVIOLET = "33[35m"
CBEIGE  = "33[36m"
CWHITE  = "33[37m"

CBLACKBG  = "33[40m"
CREDBG    = "33[41m"
CGREENBG  = "33[42m"
CYELLOWBG = "33[43m"
CBLUEBG   = "33[44m"
CVIOLETBG = "33[45m"
CBEIGEBG  = "33[46m"
CWHITEBG  = "33[47m"

CGREY    = "33[90m"
CRED2    = "33[91m"
CGREEN2  = "33[92m"
CYELLOW2 = "33[93m"
CBLUE2   = "33[94m"
CVIOLET2 = "33[95m"
CBEIGE2  = "33[96m"
CWHITE2  = "33[97m"

CGREYBG    = "33[100m"
CREDBG2    = "33[101m"
CGREENBG2  = "33[102m"
CYELLOWBG2 = "33[103m"
CBLUEBG2   = "33[104m"
CVIOLETBG2 = "33[105m"
CBEIGEBG2  = "33[106m"
CWHITEBG2  = "33[107m"

Here is the code to generate the test:

x = 0
for i in range(24):
  colors = ""
  for j in range(5):
    code = str(x+j)
    colors = colors + "33[" + code + "m33[" + code + "m33[0m "
  print(colors)
  x = x + 5

Answer rating: 137

Here"s a solution that works on Windows 10 natively.

Using a system call, such as os.system(""), allows colours to be printed in Command Prompt and Powershell natively:

import os

# System call
os.system("")

# Class of different styles
class style():
    BLACK = "33[30m"
    RED = "33[31m"
    GREEN = "33[32m"
    YELLOW = "33[33m"
    BLUE = "33[34m"
    MAGENTA = "33[35m"
    CYAN = "33[36m"
    WHITE = "33[37m"
    UNDERLINE = "33[4m"
    RESET = "33[0m"

print(style.YELLOW + "Hello, World!")

Note: Windows does not fully support ANSI codes, whether through system calls or modules. Not all text decoration is supported, and although the bright colours display, they are identical to the regular colours.

Thanks to @j-l for finding an even shorter method.

tl;dr: Add os.system("")

Answer rating: 89

sty is similar to colorama, but it"s less verbose, supports 8-bit and 24-bit (RGB) colors, supports all effects (bold, underline, etc.) allows you to register your own styles, is fully typed, supports muting, is really flexible, well documented and more...

Examples:

from sty import fg, bg, ef, rs

foo = fg.red + "This is red text!" + fg.rs
bar = bg.blue + "This has a blue background!" + bg.rs
baz = ef.italic + "This is italic text" + rs.italic
qux = fg(201) + "This is pink text using 8bit colors" + fg.rs
qui = fg(255, 10, 10) + "This is red text using 24bit colors." + fg.rs

# Add custom colors:

from sty import Style, RgbFg

fg.orange = Style(RgbFg(255, 150, 50))

buf = fg.orange + "Yay, Im orange." + fg.rs

print(foo, bar, baz, qux, qui, buf, sep="
")

prints:

Enter image description here

Demo:

Enter image description here

Answer rating: 62

Rich is a relatively new Python library for working with color in the terminal.

There are a few ways of working with color in Rich. The quickest way to get started would be the rich print method which renders a BBCode-like syntax in to ANSI control codes:

from rich import print
print("[red]Color[/] in the [bold magenta]Terminal[/]!")

There are other ways of applying color with Rich (regex, syntax) and related formatting features.

Screenshot of Rich





Get Solution for free from DataCamp guru