Maybe it helps to first understand what is happening there:
print()
is writing to the standard output and it is writing everything there including the w
and the backspace.
Now something has to display it. Most likely a terminal emulator.
What theoretically would happen is that the w
was displayed and then deleted, but it was not flushed and was to fast for it to actually happen.
So real-life applications will almost always use \b at the beginning of the printed text.
I wrote a short example that will have a little spinner on a progress indicator. The example print "-"
followed by "\b\\"
(deleting the -
and replacing it with \
) followed by "\b|"
(deleting the \
and replacing it with |
) and so on.
That way -
\
|
/
-
\
|
/
looks like an animated rotating line.
#!/usr/bin/env python3
import time
spinner="\\|/-"
print ("----------\r", end='', flush=True)
for pos in range(10):
print ("-", end='', flush=True)
for spin in range(25):
#here should be a break as soon as some task proceeded further
time.sleep(0.1)
print ("\b" + spinner[spin % 4], end='', flush=True)
print ("\b*", end='', flush=True)
print ()
P.S.: A lot of existing programs use control characters like \b
\r
\033
to display a status line. Most popular is probably wget. I have also seen such output by at least one python script (although I cant remember which one any more)
\b
char, but I'm more interested in the real-life applications of this (or if there aren't any, then the historical reasons for it). – Armandoarmature