Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Print to one line with time delay between prints

I want to make (for fun) python print out 'LOADING...' to console. The twist is that I want to print it out letter by letter with sleep time between them of 0.1 seconds (ish). So far I did this:

from time import sleep
print('L') ; sleep(0.1)
print('O') ; sleep(0.1)
print('A') ; sleep(0.1)
etc...

However that prints it to separate lines each.

Also I cant just type print('LOADING...') since it will print instantaneously, not letter by letter with sleep(0.1) in between.

The example is trivial but it raises a more general question: Is it possible to print multiple strings to one line with other function being executed in between the string prints?

like image 257
MarcinKonowalczyk Avatar asked Dec 20 '22 03:12

MarcinKonowalczyk


2 Answers

In Python2, if you put a comma after the string, print does not add a new line. However, the output may be buffered, so to see the character printed slowly, you may also need to flush stdout:

from time import sleep
import sys
print 'L',
sys.stdout.flush()
sleep(0.1)

So to print some text slowly, you could use a for-loop like this:

from time import sleep
import sys

def print_slowly(text):
    for c in text:
        print c,
        sys.stdout.flush()
        sleep(0.5)

print_slowly('LOA')

In Python3, change

print c,

to

print(c, end='')
like image 98
unutbu Avatar answered Dec 27 '22 12:12

unutbu


You can also simply try this

from time import sleep
loading = 'LOADING...'
for i in range(10):
    print(loading[i], sep=' ', end=' ', flush=True); sleep(0.5)
like image 33
Zeeshan Rizvi Avatar answered Dec 27 '22 10:12

Zeeshan Rizvi