-1

I am testing out the print() function and tried this:

>>> import sys
>>> for i in range(3):
        print('\r',i,end='',file=sys.stdout)

I want the command to print 0 then 1 then 2 to the console each replacing the one before, but the result is an input request that looks like this:

2 >>> 

why does this happen and how can I fix it?

Edit: better example

1 Answers1

3

Consider a simpler example:

>>> print('test')
test
>>>

Now add end='' to suppress the newline:

>>> print('test', end='')
test>>>

Without the newline, the prompt is displayed immediately after the string test; the cursor was never moved to the next line.

Now add the carriage return:

>>> print('\r', 'test', end='')
 test>>>

The \r doesn't really do anything: it causes the cursor to move to the beginning of the current line, but the cursor is already there. However, print does output a space before printing the next string, and as before, no newline is printed to move the cursor to the next line.

Here's an example where \r does have an effect. Compare

>>> print('foo', 'bar', end='')
foo bar>>>

with

>>> print('123456789', '\r', 'bar', end='')
 bar>>> 9

123456789 is printed, but the \r moves the cursor so that the space and bar overwrites the 1234. The prompt and following space output by the interpreter itself overwrites 5678.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
chepner
  • 497,756
  • 71
  • 530
  • 681
  • but why exactly does it print `bar>>> ` to the console and not just `bar`? – a_random_programmer Sep 11 '19 at 19:18
  • 2
    The `>>>` is part of the next prompt for the interpretter. Because you specified `end = ""`, the cursor will be at the end of your string and that's where the prompt will go. If you want it to appear on the next line (probably like you are accustomed to) then you need to print a final new line, which puts the cursor at the start of the next line. – SyntaxVoid Sep 11 '19 at 19:26
  • Thanks, that answered my question – a_random_programmer Sep 11 '19 at 19:31