pythonstdoutsleep

Slow printing with sleep, "print()" outputs all characters at once, but "sys.stdout.write()" prints them on separate lines


I want to print characters of a string slowly on the terminal on the same line. I used this code:

for i in "Hello":
    print(i, end='')
    time.sleep(0.2)

This code waits for 0.2 × 5 (length of "Hello") seconds and prints all the characters at once. When I use the sys.stdout.write() function instead of print, it prints the characters line by line instead of on the same line.

How do I print characters on same line with delay?


Solution

  • import sys
    import time
    
    for c in "Hello":
        sys.stdout.write(c)
        sys.stdout.flush() # <- add this 
        time.sleep(0.2)
    

    Or use the flush parameter in the python 3 print function

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