Python sign loading, overwriting console line

Viewed 160

So I have this code and I have no idea how to run it in only one line by just overwriting the previous output if you know what I mean. Here is the code:

import time

signs = ["|", "/", "-", "\\"]
while True:
    for i in range(4):
         print("\r" + signs[i].format(i))
         time.sleep(1)

I would be very pleased if you could help me

2 Answers

You have to add end='\r' to your print statement, so this small change should do the job as you desired:

import time

signs = ["|", "/", "-", "\\"]
while True:
    for i in range(4):
         print(signs[i].format(i), end='\r')
         time.sleep(1)

By default it is \n so next line symbol, but with \r (carriage return) the current line will be overwritten by the next output.
It can cause problems though if the previous output is longer than the one following, then it does only overwrite as much characters as the new output has, the rest remains. In such cases it can help to add some whitespaces at the end of the output to fill the difference in sequence length.
Generally the behaviour is dependent on the used output i.e. Shell, Idle, writing to file, Eclipse, PyCharm etc. Some output shells may not support this command.

This will do it:

from __future__ import print_function # only needed for python 2.x
import time, sys

signs = ["|", "/", "-", "\\"]
while True:
    for i in range(4):
         print("\r" + signs[i].format(i), end="", flush=True)
         #print("\r" + signs[i].format(i), end="") # use this instead of above in python 2.x
         #sys.stdout.flush() # only needed for python 2.x
         time.sleep(1)
Related