Ayush Gupta
Ayush Gupta

Reputation: 33

How to overwrite printed one liners in Python?

I am currently working on a random password generator which will generate a new password every 10 seconds. I know how to time loop the program but the problem is I don't want the previous password to stay on screen when a new one is generated.

The code is:

import random , time
while True:
    for i in range(6):
        print(random.randint(0,9), end=" ")
    time.sleep(2)
    print(" ")

The output is:

Output1
Output2
etc.

I want the Output2 to overwrite Output1 Thanks!

Upvotes: 2

Views: 35

Answers (1)

Gino Mempin
Gino Mempin

Reputation: 29688

You just need to print with end='\r' (carriage return).

while True:
    for i in range(6):
        print(random.randint(0, 9), end=" ")
    time.sleep(2)
    print(end="\r")

By default, print uses end='\n' (new line) as the default. By changing it to carriage return, you force it to rewind the cursor to the start of the line. As long as the next line being printed is of the same length, it overwrites the previous one.

Upvotes: 1

Related Questions