This is my note on how to print formatted text and colors in terminal using Python. There are several methods to output colored text to terminal.
Terminal can be so plain. And formatted text (aka styled text or rich text) can be used as opposed to plan text, has styling info like:
- color (text and background)
- style (bold and italic)
- others (strike-through, underline)
1. Using ANSI Escape Codes
ANSI escape codes are used to control the formatting and color in Linux terminal. To encode this formatting info, certain sequences of bytes are embedded into the text, which the terminal looks for and interprets as commands and executes them.
print('\x1b[3;31;43m' + 'Hello world!' + '\x1b[0m')
The python statement above will produce the output in "red" text-color, with "yellow" background, and "italic" style.
The general syntax is \x1b[A;B;C and the first ANSI escape code used is \x1b[3;31;43m . The second ANSI escape code used is \x1b[0m , and this is the code used to reset the color/style to defaults values.
A is for text formatting style, ranges from 1 to 9.
- 1 : bold
- 2 : faint
- 3 : italic
- 4 : underline
- 5 : blinking
- 6 : fast blinking
- 7 : reverse
- 8 : hide
- 9 : strikethrough
B is for text color, ranges from 30 t0 37.
C is for background color, ranges from 40 to 47.
- 30/40 : black
- 31/41 : red
- 32/42 : green
- 33/43 : yellow
- 34/44 : blue
- 35/45 : magenta
- 36/46 : cyan
- 37/47 : white
2. Using built-in modules : colorama, termcolor
Example of using colorama
from colorama import init, Fore, Back, Style
init (autoreset=True, strip=False)
print(Fore.RED + + Back.GREEN + Style.DIM + f'Red text on Green in dim')
print(f'Normal')
Example of using termcolor
>>> from termcolor import colored
>>> print(colored('Hello, World!', 'green', 'on_red'))
A more complex example:
# Python program to print
# colored text and background
import sys
from termcolor import colored, cprint
text = colored('Hello, World!', 'red', attrs=['reverse', 'blink'])
print(text)
cprint('Hello, World!', 'green', 'on_red')
print_red_on_cyan = lambda x: cprint(x, 'red', 'on_cyan')
print_red_on_cyan('Hello, World!')
print_red_on_cyan('Hello, Universe!')
for i in range(10):
cprint(i, 'magenta', end=' ')
cprint("Attention!", 'red', attrs=['bold'], file=sys.stderr)
Links
- https://www.geeksforgeeks.org/print-colors-python-terminal/
- https://www.geeksforgeeks.org/formatted-text-linux-terminal-using-python/