Clear Console in Python

hi there I will give an explanation. You can essentially print something called an ANSI code which when printed the computer instead of giving text interprets as something. For this case we can use one of the following:

# method 1, slow
import os
os.system('clear')


# method 2, faster
print("\033[2J\033[H", end="", flush=True) # clears, ensures no new line
                                           # and ensures immediate print
# the ansi code here is interpreted as clearing the screen with `\033[2J` but it
# doesn't move the cursor back to the beginning which is why `\033[H` is used 

# method 3 simplest
print("\033c", end="", flush=True) # see above for why there are other params included
# this has some benchmarks which say it is also the fastest

4 Likes