ANSI escape codes can change terminal text colors. Print a color code before the text and a reset code after it.
How to Use a Color
Store the codes in variables and insert them into an f-string:
RED = '\033[31m'
RESET = '\033[0m'
print(f'{RED}Red text{RESET}')
print('Normal text')
The \033 sequence represents the special Escape character. Always add RESET after colored text, or later output may remain colored.
Standard Text Colors
| Color | Python code |
|---|---|
| Black | '\033[30m' |
| Red | '\033[31m' |
| Green | '\033[32m' |
| Yellow | '\033[33m' |
| Blue | '\033[34m' |
| Magenta | '\033[35m' |
| Cyan | '\033[36m' |
| White | '\033[37m' |
Black and white depend on the terminal theme. For example, black text may be difficult to see on a dark background.
Bright Text Colors
| Color | Python code |
|---|---|
| Bright black (gray) | '\033[90m' |
| Bright red | '\033[91m' |
| Bright green | '\033[92m' |
| Bright yellow | '\033[93m' |
| Bright blue | '\033[94m' |
| Bright magenta | '\033[95m' |
| Bright cyan | '\033[96m' |
| Bright white | '\033[97m' |
Background Colors
Background colors use codes from 40 to 47:
| Background | Python code |
|---|---|
| Black | '\033[40m' |
| Red | '\033[41m' |
| Green | '\033[42m' |
| Yellow | '\033[43m' |
| Blue | '\033[44m' |
| Magenta | '\033[45m' |
| Cyan | '\033[46m' |
| White | '\033[47m' |
Reset Formatting
RESET = '\033[0m'
This code resets the text color, background, and other styles. Place it immediately after the colored content:
GREEN = '\033[32m'
RESET = '\033[0m'
status = f'{GREEN}Systems ready{RESET}'
print(status)
Clearing the Screen for Animation
ANSI codes can do more than change colors. The \033[2J sequence clears the screen, while \033[H moves the cursor to the top-left corner. Store them together when drawing a new frame:
CLEAR = '\033[2J\033[H'
print(CLEAR, end='')
print('New frame')
The end='' argument avoids adding a line break after the clear code, so the new frame starts at the top position.
Some browser-based output areas do not support screen clearing. If the code appears as [2J and [H characters, check its spelling and then ask your mentor whether the current terminal supports ANSI sequences.
A Colored Multiline String
CYAN = '\033[96m'
RESET = '\033[0m'
rocket = fr"""{CYAN}
/\
/__\
{RESET}"""
print(rocket)
print('Color reset')
The f prefix inserts variable values while r preserves backslashes written inside the drawing.
If the Color Does Not Appear
- Confirm that you used a backslash
\, not a forward slash/. - Check the final letter
m:'\033[31m'. - If
{RED}appears as text, addfbefore the opening quote. - If characters such as
[31mappear, the output area may not support ANSI codes. - Colors can look slightly different across terminals and themes.
ANSI codes only control output formatting. Do not print control sequences taken from untrusted user input.
๐ฌ Comments (0)
No comments yet
Be the first to share your opinion about this article!