Do you know how to clear code using python? I am very stuck on it as am new
Hey @21Serjeante, welcome to the community!
You can use the Replit package:
from replit import clear
...
clear()
Welcome to Ask! The solution proposed by Qwerty works. To make it work when you’re not on Replit, use this:
clear = lambda: print("\033c", end="", flush=True)
clear()
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
This is what replit.clear()
does btw. It’s harder to remember so I just recommend that people use from replit import clear
.
My solution does work when you’re not on Replit. pip install replit
. There.
yeah I just was making sure I explained
If storage is a concern (replit
has a lot of dependencies), my main package (firepup650
) also contains the same clear that replit
does. (With an optional boolean parameter to use os.system("clear||cls")
instead)
But why? It’s so much slower
Mainly just so the option is there, should someone want it.