如何将字符串“ hello world”打印到一行上,但一次打印一个字符,从而在打印每个字母之间会有延迟?我的解决方案要么导致每行一个字符,要么立即延迟打印整个字符串。这是我最近得到的。import timestring = 'hello world'for char in string: print char time.sleep(.25)
3 回答

摇曳的蔷薇
TA贡献1793条经验 获得超6个赞
这里有两个技巧,您需要使用流将所有内容放在正确的位置,还需要刷新流缓冲区。
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")

UYOU
TA贡献1878条经验 获得超4个赞
这是Python 3的简单技巧,因为您可以指定函数的end参数print:
>>> import time
>>> string = "hello world"
>>> for char in string:
print(char, end='')
time.sleep(.25)
hello world

牛魔王的故事
TA贡献1830条经验 获得超3个赞
import sys
import time
string = 'hello world\n'
for char in string:
sys.stdout.write(char)
sys.stdout.flush()
time.sleep(.25)
添加回答
举报
0/150
提交
取消