Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
468 views
in Technique[技术] by (71.8m points)

console - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...