【发布时间】:2012-02-12 03:04:15
【问题描述】:
如何将字符串“hello world”打印在一行上,但一次打印一个字符,以便在每个字母的打印之间存在延迟?我的解决方案要么导致每行一个字符,要么一次延迟打印整个字符串。这是我得到的最接近的。
import time
string = 'hello world'
for char in string:
print char
time.sleep(.25)
【问题讨论】:
标签: python
如何将字符串“hello world”打印在一行上,但一次打印一个字符,以便在每个字母的打印之间存在延迟?我的解决方案要么导致每行一个字符,要么一次延迟打印整个字符串。这是我得到的最接近的。
import time
string = 'hello world'
for char in string:
print char
time.sleep(.25)
【问题讨论】:
标签: python
这里有两个技巧,您需要使用流将所有内容放在正确的位置,还需要刷新流缓冲区。
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")
【讨论】:
sys.stdout.write(c) 在我的系统上运行良好。
这是 Python 3 的一个简单技巧,因为您可以指定 print 函数的 end 参数:
>>> import time
>>> string = "hello world"
>>> for char in string:
print(char, end='')
time.sleep(.25)
hello world
玩得开心!结果现在是动画的!
【讨论】:
print(char, end='', flush=True)
import sys
import time
string = 'hello world\n'
for char in string:
sys.stdout.write(char)
sys.stdout.flush()
time.sleep(.25)
【讨论】:
我遇到了同样的问题,并提出了不同的解决方案。 刷新缓冲区没有帮助。操作系统:Windows 10,python 3.7.4 64 位
代码无效
[while loop]
[if statement]
try:
playsound(path)
time.sleep(60)
工作代码
import time
from time import sleep
[while loop]
[if statement]
try:
playsound(path)
sleep(60)
【讨论】: