[英]How to insert sleep into a list
我希望创建一个小模块来实现文本滚动的能力。 到目前为止,我已经尝试了一些事情,这就是我所坐的:
from time import sleep
def text_scroll(x):
x = x.split()
#here is where I'd like to add the sleep function
x = " ".join(x)
print x
text_scroll("hello world.")
有了这一切,我希望让它打印“你好”,睡一会,“世界”。 到目前为止我得到的最好的是它返回 None 而不是实际暂停。
试试下面的代码:
from time import sleep
from sys import stdout
def text_scroll(text):
words = text.split()
for w in words:
print w,
stdout.flush()
sleep(1)
打印末尾的逗号不添加新行 '\\n'。 flush() 函数将单词刷新到屏幕中(标准输出)。
如果是python 2.7,你可以做以下,这是火山建议的。
from time import sleep
def text_scroll(x):
for word in x.split():
print word,
sleep(1)
text_scroll("Hello world")
这是有效的,因为它将输入拆分为单个单词,然后打印它们,在每个单词之间休眠。 print word,
是 python 2.7 的打印word
,没有换行符,
。
你的不起作用有几个原因:
def text_scroll(x):
x = x.split()
#here is where I'd like to add the sleep function
x = " ".join(x)
这个函数不会对它产生的变量做任何事情,它会破坏它:
def text_scroll(x):
x = x.split() # x = ["Hello", "world"]
#here is where I'd like to add the sleep function
x = " ".join(x) # x = "Hello world"
它实际上对结果没有任何作用,所以它被扔掉了。 但同样重要的是要意识到,因为它是一个def
,它在被调用之前不会执行。
当您print x
, x
尚未设置,因此它应该给您一个NameError: name 'x' is not defined
最后,您调用不输出任何内容的函数text_scroll("hello world.")
并完成。
for word in x.split():
print word,
time.sleep(1)
逗号可防止打印向输出添加换行符
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.