Hash
Hash

Reputation: 146

How to overwrite a line with carriage return, using a for-loop in Python?

I'm trying to print out a string with the end=\r to send the cursor back to beginning of the line, and overwrite the printed string using a for loop

This is the code thus far I got :

import time

print("░░░░░░░░░░░░░", end='\r')
for i in ("SECRET"):
    print(i ,end='')
    time.sleep(0.3)

Ideally, it should slowly overwrite some of the dotted pattern characters with characters from `"SECRET" every 0.3 seconds.

However, when run, the for loop instead iterates and prints characters on a single space, overwriting the characters it prints out itself, instead of advancing to the next available space, overwriting the dot pattern there and typing out the remaining characters in the string it iterates over

Removing the entire print statement associated with the dotted pattern characters allows the loop to function normally, printing out the string it iterates over properly, however, it is needed for the loop to print out the string and overwrite the dotted characters

Essentially, I want to overwrite some of the dotted pattern characters one by one using characters from the string the for loop iterates over, with the help of \r

I am on Ubuntu Studio

Upvotes: 1

Views: 1471

Answers (2)

forever
forever

Reputation: 219

you can't overwrite characters in python. you can, though, clear the whole screen by using os.system('cls') on windows or os.system('clear') on linux and unix. here is the full code:

import time, os

output = '░░░░░░░░░░░░░'
for i in range(7):
    print(output)
    output = "SECRET"[:i]+output[i:]
    time.sleep(0.3)
    if os.name == 'nt': #on windows
       os.system("cls")
    else:
       os.system("clear") #not on windows
print(output)

also, this will only work when you are not running from the shell and if you want to see the full output, write time.sleep(1) at the end.

Upvotes: 0

John Gordon
John Gordon

Reputation: 33335

Screen output is line-buffered. This means that when you print something followed by a newline it appears on the screen immediately, but if you print something without a newline it might take a while to appear.

This is what's happening to you -- the output inside the for loop is not followed by a newline, so it doesn't appear onscreen immediately.

You can add flush=True to the print call to force the output to appear immediately instead of waiting:

print(i, end='', flush=True)

Upvotes: 1

Related Questions