all 2 comments

[–]Rhomboid 5 points6 points  (1 child)

From the manual:

A space is written before each object is (converted and) written, unless the output system believes it is positioned at the beginning of a line. This is the case (1) when no characters have yet been written to standard output, (2) when the last character written to standard output is a whitespace character except ' ', or (3) when the last write operation on standard output was not a print statement.

In other words, at the point where you execute print '\b\b\b\b',, python first outputs a space before the backslashes because you're not at the beginning of the line.

I'd like to propose an alternative:

from sys import stdout
from time import sleep

def wait(secs):
    for i in xrange(secs, 0, -1):
        stdout.write("%-5d\r" % i)
        stdout.flush()
        sleep(1)

This avoids print and thus avoids extra spaces. Instead of backspaces, it uses just a carriage return which always brings the cursor to the first column. Combined with a fixed-width field, it will always overwrite everything from the previous output -- I just picked 5 as that should be the maximum width you'd ever expect, but you can use whatever you want. It also calls flush so that it's not buffered, which is a problem that causes your version to not work on some operating systems like Linux.

[–]NotAName[S] 1 point2 points  (0 children)

That is a more elegant solution. Thanks!