clear the screen

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sun Apr 21 08:49:35 EDT 2013


On Sat, 20 Apr 2013 19:45:46 -0700, Yuanyuan Li wrote:

> How to clear the screen? For example, in the two player game. One player
> sets a number and the second player guesses the number. When the first
> player enters the number, it should be cleared so that the second number
> is not able to see it. My question is how to clear the number. Thank
> you!


What sort of screen? A GUI window, or in a terminal?

If you have a GUI window, you will need to read the documentation for 
your GUI toolkit.

If it is in a terminal, that will depend on the terminal. The best 
solution is to use Curses, if you can, but that is Unix only.

Another solution is this:

print("\x1b[H\x1b[2J")

although that only works in some terminals, and it will not work in IDLE.


Another solution is this:

import os
result = os.system("clear")  # Linux, Mac, Unix

or for Windows:

result = os.system("cls")


but again, it may not work in IDLE.


Last but not least, if everything else fails, try printing a whole lot of 
blank lines:

print("\n"*100)


ought to do it on all but the tallest terminals, and amazingly, it even 
works in IDLE!



-- 
Steven



More information about the Python-list mailing list