如何将字符串“hello world”打印到一行上,但一次只打印一个字符,以便在每个字母的打印之间存在延迟?我的解决方案要么导致每行一个字符,要么一次延迟打印整个字符串。这是我得到的最接近的。如何在一行上一次打印一个字符?
import time
string = 'hello world'
for char in string:
print char
time.sleep(.25)
如何将字符串“hello world”打印到一行上,但一次只打印一个字符,以便在每个字母的打印之间存在延迟?我的解决方案要么导致每行一个字符,要么一次延迟打印整个字符串。这是我得到的最接近的。如何在一行上一次打印一个字符?
import time
string = 'hello world'
for char in string:
print char
time.sleep(.25)
这里有两个窍门,您需要使用流来获取正确位置的所有内容,并且还需要刷新流缓冲区。
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")
import sys
import time
string = 'hello world\n'
for char in string:
sys.stdout.write(char)
sys.stdout.flush()
time.sleep(.25)
下面是Python 3的一个简单的技巧,因为你可以指定end
参数print
功能:
>>> import time
>>> string = "hello world"
>>> for char in string:
print(char, end='')
time.sleep(.25)
hello world
玩得开心!结果现在动画!
为什么字符串插值? 'sys.stdout.write(c)'在我的系统上工作得很好。 – Blair 2012-09-05 21:27:05