Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

python - How to print one character at a time on one line?

How would one print the string "hello world" onto one line, but one character at a time so that there is a delay between the printing of each letter? My solutions have either resulted in one character per line, or a delayed printing of the entire string at once. This is the closest I've gotten.

import time
string = 'hello world'
for char in string:
    print char
    time.sleep(.25)
Question&Answers:os

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

1 Answer

0 votes
by (71.8m points)

Two tricks here, you need to use a stream to get everything in the right place and you also need to flush the stream buffer.

import time
import sys

def delay_print(s):
    for c in s:
        sys.stdout.write(c)
        sys.stdout.flush()
        time.sleep(0.25)

delay_print("hello world")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...