如何让Python按一个数字或字母逐个输入,或以延迟的速度输入?
好的,这个问题可能有点难以表达,但请耐心听我说。
我想让使用“while True”这个命令时的效果看起来更酷一点。
我想要的是让它慢慢地输入内容,或者说一个字母一个字母地输入。
比如,这里是我的代码。
while True:
print ("010101010101010101010101010101")
print ("010101010101001010101010101010")
print ("010101010101010101010101010101")
当我这样做的时候,它显然会快速重复我在文件中输入的命令。
我知道可以用下面的方式:
import time time.sleep(5)
但是我希望它一个字母一个字母地输入,而不是每5秒才输入一次。
希望你能理解我想问的是什么。非常感谢你的帮助。
2 个回答
1
听起来你想在每个字符之间加个延迟,所以你需要在每个字符之间调用一下 sleep
函数:
import time
while True:
for binary_char in "10101010101010101":
time.sleep(5) # Replace this with a much smaller number, probably
print binary_char, # Remove trailing comma to print each character on new line
2
这里有一个可能的解决办法:
import sys
import time
def cool_print(str):
for char in str:
sys.stdout.write(char)
sys.stdout.flush()
time.sleep(0.05) # Or whatever delay you'd like
print # One last print to make sure that you move to a new line
然后你就可以用 cool_print("010101010101010101010101010101")
来代替 print ("010101010101010101010101010101")
了。