我试图做一个文字游戏,它将开始一个计时器,将添加一个字母,形成一个字符串每0.05秒,所以它看起来像是有人在键入一个句子。
例如。“你好,这是一个测试”,从h开始,然后e,l,l,o,在一行上打印字母之间的时间间隔。
import time
string = "Hello, this is a test"
count=1
while count >0:
time.sleep(0.05)
print(string[:1]),这是我尝试过的代码,但我只是迷路了,不知道如何继续。有什么办法能让我做到这一点吗?
发布于 2013-09-25 15:32:41
将while循环替换为对要打印的字符串进行迭代的for循环。这将给你的每一个字母轮流,并停止你的循环在最后。我还建议将这种行为置于这样的功能中:
def typeText(text, delay=0.05):
for character in text:
print character,
time.sleep(delay)
typeText("Hello, this is a text")为了解决空间问题,您可以有三个选项,以便从最大到最小的副作用:
print作为一个函数,其中包含一个可以设置为空字符串的end参数;from __future__ import print_function,它将为您提供相同的打印功能,而不需要python3的所有其他警告;print替换为sys.stdout.write()。默认情况下,这个函数是打印包的。发布于 2013-09-25 15:23:16
这就是做这个的方法,
编辑:由于OP在打印每个字符后不需要空格,所以我设置了end=''
import time
string = "Hello, this is a test"
count=0
while count<len(string):
time.sleep(0.05)
print (string[count],end='')
count = count+1发布于 2013-09-25 15:26:56
试着做这样的事情:
import time
string = "Hello, this is a test"
count=1
for i in string:
time.sleep(0.05)
print(i)https://stackoverflow.com/questions/19008873
复制相似问题