This is a very old thread, but here's a very thorough answer and sample code.
\r
is the string representation of Carriage Return from the ASCII character set. It's the same as octal 015
[chr(0o15)
] or hexidecimal 0d
[chr(0x0d)
] or decimal 13
[chr(13)
]. See man ascii
for a boring read. It (\r
) is a pretty portable representation and is easy enough for people to read. It very simply means to move the carriage on the typewriter all the way back to the start without advancing the paper. It's the CR
part of CRLF
which means Carriage Return and Line Feed.
print()
is a function in Python 3. In Python 2 (any version that you'd be interested in using), print
can be forced into a function by importing its definition from the __future__
module. The benefit of the print
function is that you can specify what to print at the end, overriding the default behavior of \n
to print a newline at the end of every print()
call.
sys.stdout.flush
tells Python to flush the output of standard output, which is where you send output with print()
unless you specify otherwise. You can also get the same behavior by running with python -u
or setting environment variable PYTHONUNBUFFERED=1
, thereby skipping the import sys
and sys.stdout.flush()
calls. The amount you gain by doing that is almost exactly zero and isn't very easy to debug if you conveniently forget that you have to do that step before your application behaves properly.
And a sample. Note that this runs perfectly in Python 2 or 3.
from __future__ import print_function
import sys
import time
ANS = 42
FACTORS = {n for n in range(1, ANS + 1) if ANS % n == 0}
for i in range(1, ANS + 1):
if i in FACTORS:
print('\r{0:d}'.format(i), end='')
sys.stdout.flush()
time.sleep(ANS / 100.0)
else:
print()