ashutosh_paul
ashutosh_paul

Reputation: 53

How to sleep in Python 3 and remain in the same line?

  1. I want to print a message with end=''
  2. Sleep for 1 second
  3. Remain on the same line
  4. Erase the previous message using '\b'
  5. Print a new message
  6. Back to step 1

Example:

First output: 1 Second output: 2 Third output: 3 Remains in the same line

NOT: 123

Upvotes: 2

Views: 276

Answers (1)

Patrick Haugh
Patrick Haugh

Reputation: 60954

Are you set on using \b? You can use \r to move the cursor back to the beginning of the line, which will let you write over stuff that is already there. If there's a chance that later lines will be shorter than previous ones, you should pad the new lines with whitespace on the right. Something like:

def f(x):
    for i in range(1, x+1):
        print(end='\r', flush=True)
        print('**{}**'.format(i), end='', flush=True)
        time.sleep(1)

f(3)

Upvotes: 1

Related Questions