我想做一个脚本,一个接一个地键入字符串字母
def autotype(info):
count = len(info) #Countign number of letters of the string
splitlist = list(info)
i = int(count) #getting an error on this line! it accept i=int(0) but my loop doesnt work because of this
while i>0:
sys.stdout.write(splitlist[i])
time.sleep(0.2)
i -= 1
info = str("hello world")
autotype(info)
错误是:列表索引超出范围 我怎么修?在
你的剧本很不象话。这里也有同样的方法。字符串是ITerable,因此:
这就是你所需要的。在
从
i=len(info)
开始循环,这比字符串中的最后一个索引多一个。字符串(或其他iterable)中的最后一个索引是len(string) - 1
,因为索引从0
开始。在请注意,在Python中,您可以(并鼓励)使用自然语言构造以及集合易于迭代的事实:
既然您已经在评论中澄清了您实际上希望继续阅读文本,那么您可以去掉
^{pr2}$reversed
位。您发布的代码将在文本中向后迭代,而不是向前迭代——使用标准迭代技术的另一个好处是可以更容易地看到您是否做了不想做的事情!在最后,正如其他人所提到的,您应该在每次写入之后添加对
sys.stdout.flush()
的显式调用,因为否则无法保证您将定期看到输出(它可以写入缓冲区,但直到很晚才会刷新到屏幕)。在列表的长度是列表中元素的数量。但是,列表从索引
0
开始,因此它们将以索引length - 1
结束。所以,要按原样修复代码,它应该是i = count - 1
。(不需要将其转换为int
,它已经是一个了。)更好的是,与其在
while
循环中使用计数器进行迭代,不如使用for
循环。可以使用for
循环迭代字符串中的字符。在您也不需要将
"hello world"
转换为字符串-它已经是一个了。在相关问题 更多 >
编程相关推荐