如何在一行上一次打印一个字符? [英] How to print one character at a time on one line?

查看:55
本文介绍了如何在一行上一次打印一个字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将字符串hello world"打印到一行上,但一次一个字符,以便在每个字母的打印之间存在延迟?我的解决方案要么导致每行一个字符,要么一次延迟打印整个字符串.这是我得到的最接近的.

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)

推荐答案

这里有两个技巧,您需要使用流将所有内容放在正确的位置,您还需要刷新流缓冲区.

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")

这篇关于如何在一行上一次打印一个字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆