Python: Print to one line with time delay between prints

这一生的挚爱 提交于 2019-12-21 20:38:58

问题


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?


回答1:


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)



回答2:


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='')



回答3:


from time import sleep

myList = ['Let this be the first line', 'Followed by a second line', 'and a third line']

for s in myList:
    print(s) ; sleep(0.6)



回答4:


Updated to print all the letters on one line.

from time import sleep
import sys
sys.stdout.write ('L') ; sleep(0.1)
sys.stdout.write ('O') ; sleep(0.1)
sys.stdout.write ('A') ; sleep(0.1)
...
sys.stdout.write ('\n')

etc...

or even:

from time import sleep
import sys
output = 'LOA...'
for char in output:
    sys.stdout.write ('%s' % char)
    sleep (0.1)

sys.stdout.write ('\n')



回答5:


To type a string one letter at a time all you've got to do is this:

import sys 
import time

yourWords = "whatever you want to type letter by letter"

for char in yourWords:
sys.stdout.write(char)
time.sleep(0.1)


来源:https://stackoverflow.com/questions/17432478/python-print-to-one-line-with-time-delay-between-prints

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!