What is this command?

print(chr(27) + “[2J”)

someone pls. give a sample how to use it. thanks

Breaking down the command in three parts,

  • print() is the most common way to display output in python.
  • chr(x) would give you the ASCII character associated with the number x. For example, chr(97) would return 'a'.
  • "[xyz" this is a string. It is important to note that although [ may have its own meaning in python syntax, when it is quoted under string, it is simply represented with its character, so it looses any special meaning.

chr(27) is the same as '\x1b' which is the ASCII “Escape” control
character.

chr(27) + "[2J" is the same as the string '\x1b[2J' which is an ANSI
escape sequence to clear the terminal window.

That means that your terminal, or console, if it understands ANSI
escape sequences (not all terminals do), will detect when you print that
magic string and clear the window.

If you are using IDLE, or another IDE, it probably won’t work. But if
you are using your operating system’s terminal or console, it will
probably clear the screen.

This is not a Python feature, it depends entirely on the terminal or
console you are running in. If the terminal supports ANSI escape codes,
it will clear the screen, if not, it will probably just print a space
and then [2J.

2 Likes

Generally ANSI escape codes don’t work in a Windows command shell.
I like the (non-standard) colorama module, that enables ANSI control codes from within Windows.:

import colorama
colorama.init()
print(chr(27) + "[2J")   # Clears the screen on Windows, Mac, Unix
# And easy colours:
print(colorama.Fore.RED, 'Error', colorama.Style.RESET_ALL)