Add Color to Text Output in Python

thumbnail

In this tutorial, you will learn to make some of your text output to be more colorfull. To make this happen, you can use ANSI escape codes to change the color of the output in Python. You can implement this to highlight errors in the ouput program you write.

To begin, you will learn the format for the escape codes to print a statement.

print("\033[1;32;47m Bright Green  \n")

The above snippet code will show the output below:

Bright Green

How’s that possible?

Well, the above ANSI escape code will set the text color to bright green. The breakdown is explained like this:

\033[ = Escape code, this is always same

1 = Style, the number 1 mean for bold syle

32 = Text color, 32 is for bright green

47m = Background color, 47 is for White color

You find another available format from the table below.

Text Color

Code

Black

30

Red

31

Green

32

Yellow

33

Blue

34

Purple

35

Cyan

36

White

37

 

Text Style

Code

No Effect

0

Bold

1

Underline

4

Italic

3

 

Background Color

Code

Black

40

Red

41

Green

42

Yellow

43

Blue

44

Purple

45

Cyan

46

White

47

Here is the example to use the text style.

print("\033[0;30;47m Normal text\n")
print("\033[1;30;47m Bold text\n")
print("\033[3;30;47m Italic text\n")
print("\033[4;30;47m Underline text\n")

The output will be:

 

Another example to create color text output in Python.

print("\033[1;30;40m Dark Gray      \033[0m 1;30;40m       \033[0;30;47m Black      \033[0m 0;30;47m       \033[0;37;41m Black      \033[0m 0;37;41m")
print("\033[1;31;40m Bright Red     \033[0m 1;31;40m       \033[0;31;47m Red        \033[0m 0;31;47m       \033[0;37;42m Black      \033[0m 0;37;42m")
print("\033[1;32;40m Bright Green   \033[0m 1;32;40m       \033[0;32;47m Green      \033[0m 0;32;47m       \033[0;37;43m Black      \033[0m 0;37;43m")
print("\033[1;33;40m Yellow         \033[0m 1;33;40m       \033[0;33;47m Brown      \033[0m 0;33;47m       \033[0;37;44m Black      \033[0m 0;37;44m")
print("\033[1;34;40m Bright Blue    \033[0m 1;34;40m       \033[0;34;47m Blue       \033[0m 0;34;47m       \033[0;37;45m Black      \033[0m 0;37;45m")
print("\033[1;35;40m Bright Magenta \033[0m 1;35;40m       \033[0;35;47m Magenta    \033[0m 0;35;47m       \033[0;37;46m Black      \033[0m 0;37;46m")
print("\033[1;36;40m Bright Cyan    \033[0m 1;36;40m       \033[0;36;47m Cyan       \033[0m 0;36;47m       \033[0;37;47m Black      \033[0m 0;37;47m")
print("\033[1;37;40m White          \033[0m 1;37;40m       \033[0;37;40m Light Grey \033[0m 0;37;40m       \033[0;37;48m Black      \033[0m 0;37;48m")

The output will be:

001_example_output_2
001_example_output_2
Back To Top