Skip to content

Updated: 02/11/2026

Terminal colors: ANSI escape codes in Python, JavaScript, Java, PHP and C++

The console does not have to be gray. A red error message, a green “OK”, a yellow warning or a Christmas tree with colorful baubles: all of this is done with ANSI escape codes, short sequences of characters inserted into an ordinary string. The terminal does not print them; it changes the color and style of the text according to them.

This page covers the structure of a sequence, a table of codes, the 256-color palette and truecolor, examples in five languages and the most common mistakes. You can run every example in the browser, with no installation: the BitWizards console shows ANSI colors in Python, JavaScript, Java, PHP and C++.

Try your first colored string in Python (the lessons are in Polish)

How colored text in the console works

A sequence starts with the invisible ESC character (code 27, hexadecimal 1B, octal 33). It is followed by a square bracket, numbers separated by semicolons and the letter m, which means “set the text appearance”:

ESC [ 31 m        red text
ESC [ 1 ; 32 m    bold green text
ESC [ 0 m         reset: back to the default appearance

The appearance lasts until a reset. Everything a program prints after ESC[31m is red, also on the following lines, until ESC[0m appears. That is why every colored fragment should end with a reset.

In source code the ESC character is written as an escape sequence inside a string. Each language has its own way:

Language ESC written as Example: red text
Python \033, \x1b, \u001b print("\033[31mtext\033[0m")
JavaScript \x1b, \u001b console.log("\x1b[31mtext\x1b[0m")
Java \u001B, \033 System.out.println("\u001B[31mtext\u001B[0m")
PHP \e, \033 echo "\e[31mtext\e[0m";
C++ \x1b, \033 cout << "\x1b[31mtext\x1b[0m";

ANSI color codes table: text and background

The eight basic colors use codes 30-37 for text and 40-47 for the background. Bright variants are 90-97 (text) and 100-107 (background).

Color Text Bright text Background Bright background
black 30 90 40 100
red 31 91 41 101
green 32 92 42 102
yellow 33 93 43 103
blue 34 94 44 104
magenta 35 95 45 105
cyan 36 96 46 106
white 37 97 47 107

The exact shade depends on the terminal: each one has its own palette, and “bright black” (90) usually looks gray.

Text styles: bold, underline, reverse

Code Effect
0 reset: default color and style
1 bold
2 dim
3 italic
4 underline
7 reverse: text and background colors swap

Codes are combined with a semicolon in one sequence. ESC[1;4;33;44m gives bold, underlined yellow text on a blue background.

256 colors and truecolor

When eight colors are not enough, there are two extended forms:

  • 256-color palette: ESC[38;5;nm sets the text color and ESC[48;5;nm the background, where n is a number 0-255. Numbers 0-15 are the basic and bright colors, 16-231 form a 6x6x6 cube (number = 16 + 36 * r + 6 * g + b, where r, g, b are 0-5), and 232-255 are shades of gray;
  • truecolor (24-bit): ESC[38;2;r;g;bm sets the text to any RGB color and ESC[48;2;r;g;bm the background. For example ESC[38;2;255;128;0m is orange.

This Python program draws the cube of the 256-color palette as colored background:

for number in range(16, 232):
    print(f"\033[48;5;{number}m  \033[0m", end="")
    if (number - 15) % 36 == 0:
        print()

Colored text in Python (print with color)

Python needs no library for this. It is handy to keep the codes in constants and concatenate them or put them in an f-string:

RED = "\033[31m"
GREEN = "\033[32m"
BOLD = "\033[1m"
RESET = "\033[0m"

print(RED + "Error: file not found" + RESET)
print(f"{BOLD}{GREEN}Saved!{RESET} Back to plain text.")

With more messages, a small function that adds the reset itself helps:

def colored(text, code):
    return f"\033[{code}m{text}\033[0m"

print(colored("PASS", "1;32"), "test_login")
print(colored("FAIL", "1;31"), "test_logout")

Popular libraries (such as colorama or rich) do the same under the hood: they print ANSI sequences. More about the course: Python.

Console colors in JavaScript (console.log)

In Node.js and in the BitWizards console, console.log prints ANSI sequences just like other languages. ESC is written as \x1b or \u001b. The octal form \033 is deprecated in JavaScript and is a syntax error in strict mode ("use strict", modules).

const RED = "\x1b[31m";
const RESET = "\x1b[0m";

console.log(RED + "Error: file not found" + RESET);
console.log(`\x1b[1;32mSaved!${RESET} Back to plain text.`);

More about the course: JavaScript.

Console colors in Java (System.out.println)

In Java ESC is most often written as \u001B; the octal \033 works too:

public class Main {
    static final String RED = "\u001B[31m";
    static final String RESET = "\u001B[0m";

    public static void main(String[] args) {
        System.out.println(RED + "Error: file not found" + RESET);
        System.out.println("\u001B[1;32mSaved!" + RESET + " Back to plain text.");
    }
}

More about the course: Java.

Console colors in PHP (echo)

PHP has the shortcut \e for the ESC character, and \033 works too. Note: escape sequences work only in double-quoted strings "...". In single quotes '\e[31m' PHP prints a literal backslash and the letter e.

<?php
$red = "\e[31m";
$reset = "\e[0m";

echo $red . "Error: file not found" . $reset . "\n";
echo "\e[1;32mSaved!\e[0m Back to plain text.\n";

ANSI codes apply to the console (PHP run from the command line). On a web page, color is set with HTML and CSS. More about the course: PHP.

Console colors in C++ (cout)

In C++ ESC is written in hexadecimal \x1b or in octal \033:

#include <iostream>
using namespace std;

int main() {
  cout << "\x1b[31m" << "Error: file not found" << "\x1b[0m" << endl;
  cout << "\033[1;32mSaved!\033[0m Back to plain text." << endl;
  return 0;
}

More about the course: C++.

Common mistakes

  • No reset, the color “leaks”. Without ESC[0m at the end, the color carries over to the following lines, and in a real terminal sometimes even to the prompt after the program ends. Close every colored fragment with a reset.
  • The classic Windows console. The old cmd.exe console shows sequences as characters like ←[31m until the program enables VT sequence processing (this is what colorama.just_fix_windows_console() does in Python, for example). Windows Terminal and Linux and macOS terminals support ANSI out of the box.
  • IDE consoles. Some show colors (for example the VS Code terminal or the PyCharm console), others show raw characters (for example IDLE). If colors do not work, run the program in the system terminal.
  • Output to a file. When output is redirected to a file (python app.py > log.txt), the sequences end up in the file as ordinary characters. Command-line tools often turn colors off when output is not a terminal or when the NO_COLOR environment variable is set.
  • Single quotes in PHP, \033 in JavaScript. See the sections above: PHP needs double quotes, and in JavaScript \x1b is the safer choice.
  • Control sequences other than colors. Clearing the screen (ESC[2J) or moving the cursor works in a real terminal, but the BitWizards console skips these sequences and shows only colors and styles.

Project: a Christmas tree with colorful baubles

A good first project with colors combines loops, randomness and ANSI codes. The tree is green, and baubles in bright colors hang in random places. The trunk is brown from the 256-color palette. Every run gives a different tree:

import random

GREEN = "\033[32m"
TRUNK = "\033[38;5;94m"
RESET = "\033[0m"
BAUBLES = ["\033[91m", "\033[93m", "\033[94m", "\033[95m", "\033[96m"]

height = 7
for row in range(height):
    line = ""
    for _ in range(2 * row + 1):
        if random.random() < 0.2:
            line += random.choice(BAUBLES) + "o" + RESET
        else:
            line += GREEN + "*" + RESET
    print(" " * (height - row - 1) + line)
print(" " * (height - 2) + TRUNK + "###" + RESET)

The idea is described in more detail in the author’s article (in Polish) Tworzenie choinki w Pythonie: świąteczne programowanie. The colorful tree is also an example and a task in the “Kolory w konsoli” topic of each basics course (lesson list below).

Colors in the BitWizards console

The BitWizards console interprets ANSI codes in every language that runs in the browser: Python, JavaScript, Java, PHP and C++. Supported:

  • reset (0), bold (1), dim (2), italic (3), underline (4) and reverse (7);
  • text colors 30-37 and bright 90-97, backgrounds 40-47 and bright 100-107;
  • the 256-color palette (38;5;n, 48;5;n) and truecolor (38;2;r;g;b).

A color lasts until a reset and carries over to the following lines, as in a terminal. The palette is tuned for both the light and the dark theme, so text stays readable in each. Other sequences (clearing the screen, moving the cursor) are skipped. The code runs in the browser, with no compiler or interpreter to install.

Lessons: the “Kolory w konsoli” topic

At the end of the basics courses there is a topic called “Kolory w konsoli” (colors in the console) with four examples (first colored string, eight colors and bright variants, bold, underline and background, a Christmas tree with colorful baubles) and tasks: a green OK message, a traffic light, a rainbow from a loop, a progress bar, a PASS and FAIL test report and a colorful Christmas tree. The lessons are in Polish and open without logging in:

Python - JavaScript - Java - PHP - C++

Run your first colored string without logging in

Frequently asked questions

How do I print colored text in Python?

Put an ANSI sequence with a color code before the text and a reset code after it, for example print("\033[31mError\033[0m") prints the word Error in red. No library is needed: the terminal draws the color when it recognizes the sequence.

What does \033[0m mean?

It is the reset: it restores the default color and style. \033 is the ESC character written in octal (27 in decimal), [ opens the sequence, 0 is the reset code and the letter m ends a sequence that sets the text appearance.

Why do I see characters like ←[31m instead of colors?

The console does not interpret ANSI sequences. The classic Windows console (cmd.exe) behaves like this until the program enables VT mode, and so do some IDE consoles, for example IDLE. Windows Terminal, Linux and macOS terminals and the BitWizards console show colors right away.

Do ANSI colors work in Java, PHP, JavaScript and C++?

Yes. ANSI sequences are ordinary characters in a string, so they work in every language that prints text to a terminal. Only the way of writing the ESC character differs: \u001B in Java, \e in PHP, \x1b in JavaScript and C++, and usually \033 in Python.

How many colors can a terminal show?

The basic set is 8 colors plus 8 bright variants, for both text and background. Most modern terminals also support a 256-color palette (38;5;n) and full RGB color, called truecolor (38;2;r;g;b).

Start now

BitWizards is free. Try the demo without signing in, or sign in to the app to save your progress.

See how to get started