Locked learning resources

Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

ANSI Escape Sequences

Some terminals support the ability to pass in special escape sequences to alter the color, weight, and appearance of the text being printed. These escape sequences are called ANSI escape sequences, named after the ANSI standard that specifies their usage:

Python
def esc(code):
    return f'\033[{code}m'

Here’s what you’ll get:

Python
>>> print('this is ', esc('31'), 'really', esc(0), ' important', sep='')
this is really important
>>> print('this is ', esc('31;1'), 'really', esc(0), ' important', sep='')
this is really important
>>> print('this is ', esc('31;1;4'), 'really', esc(0), ' important', sep='')
this is really important

To learn more about the various ANSI, check out the Wikipedia page.

00:00 In the previous lesson, I showed you how to use pprint() (pretty print). In this one, I’ll be talking about ANSI escape sequences. Most terminals support the ability to take an escape code to control the formatting of the text. You can usually control color, bold, underline, and strikeout. Unix and Mac terminals have been supporting this with 16 colors for quite some time.

00:21 Most of them support 256 out of the box now, and some of the newer ones even support true color. Windows support is a little iffier, but the new terminal does support this mechanism.

00:32 If you’re using the older terminals, the colorama library is a good alternative to get the same effects. The standards body that set these escape codes was the ANSI standards body, so these are often referred to colloquially as ANSI escape sequences or ANSI codes. You can see a full listing of these codes at the Wikipedia page.

00:52 So, let’s see how this works. First off, I’m going to define a function that makes it easier to use these codes. This is just a typical string. The \033 is the escape code, just like a \n or \r, but this is sending a hex value through to the terminal.

01:07 The left square bracket ( [ ) is a parameter, {code} will be the code we’re displaying, which I’m going to pass in through the function, and then the m tells ANSI that it’s done. Here’s a simple example.

01:20 print() calling the escape code, passing in '31', and then calling in the escape code passing in 0. '31' turns red on, 0 turns it off. This is what it results in: this is really important, in red.

01:37 You can pass in more than just color controls. '31;1' will pass in red and bold. Finally, you can also add underscores by putting in a third parameter.

01:49 Color isn’t the only thing you can do—you can also do simple animations. In the next lesson, I’ll show you how.

Become a Member to join the conversation.