The terminal where print displays its contents is a special program that can have several capabilities - they are activated depending on the control codes you send inside the string itself in print.
So for example, to print colored text, multiple terminals but not the standard Windows terminal accept type sequences <ESC>[...m
- are called ANSI sequences, (To print the ESC code, in a Python string we use its hexadecimal ASCII code, with the sequence \x1b
.
These ANSI sequences include commands to reposition the cursor anywhere on the terminal screen - you choose the row and column where you want to print. Here is the reasonably complete documentation as well as the history of these sequences: https://en.wikipedia.org/wiki/ANSI_escape_code
Microsoft promised for this year a new terminal in Windows 10, which should replace the cmd
that should have these sequences by default. Meanwhile, you can use a program called "Cmder" which is a Unix terminal experience on Windows - or the outsourced library "Colorama" to enable ANSI sequences in the cmd
.
However, there is a simpler sequence, which works even on terminals that are with ANSI disallowed sequences, which is the backspacs character - Python has special encoding \b
for the same that can be used in strings.
In addition to this sequence, it is important to customize the print call to (1), it does not send the " n" after printing and (2) do not wait for the " n" to update the line content - these two things are done by passing the parameters end="", flush=True
to the print
.
So try this example:
import time
print("Contagem regressiva")
for i in range(10, -1, -1):
print(f"\b\b\b{i} ", end="", flush=True)
time.sleep(0.5)
In the case of the 3 " b" move the cursor back 3 positions (if it reaches column 0 he stops), and the space " " after the "{i}" ensures that it erases the second digit (the 0 of the 10), when the count becomes a single digit.