在Python中迭代字符串

2024-10-02 12:26:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我想做一个脚本,一个接一个地键入字符串字母

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)

错误是:列表索引超出范围 我怎么修?在


Tags: of字符串info脚本number键入lendef
3条回答

你的剧本很不象话。这里也有同样的方法。字符串是ITerable,因此:

def autotype(info):
    for x in info:
        sys.stdout.write(x)
        sys.stdout.flush()  # you need this, because otherwise its' buffered!
        time.sleep(0.2)

这就是你所需要的。在

i=len(info)开始循环,这比字符串中的最后一个索引多一个。字符串(或其他iterable)中的最后一个索引是len(string) - 1,因为索引从0开始。在

请注意,在Python中,您可以(并鼓励)使用自然语言构造以及集合易于迭代的事实:

for letter in reversed(info): # Much clearer way to go backwards through a string
    sys.stdout.write(letter)

既然您已经在评论中澄清了您实际上希望继续阅读文本,那么您可以去掉reversed位。您发布的代码将在文本中向后迭代,而不是向前迭代——使用标准迭代技术的另一个好处是可以更容易地看到您是否做了不想做的事情!在

^{pr2}$

最后,正如其他人所提到的,您应该在每次写入之后添加对sys.stdout.flush()的显式调用,因为否则无法保证您将定期看到输出(它可以写入缓冲区,但直到很晚才会刷新到屏幕)。在

列表的长度是列表中元素的数量。但是,列表从索引0开始,因此它们将以索引length - 1结束。所以,要按原样修复代码,它应该是i = count - 1。(不需要将其转换为int,它已经是一个了。)

更好的是,与其在while循环中使用计数器进行迭代,不如使用for循环。可以使用for循环迭代字符串中的字符。在

for ch in info:
    sys.stdout.write(ch)
    sys.stdout.flush()   # as mawimawi suggests, if you don't do this, it will
                         # actually just come out all on one line at once.
    time.sleep(0.2)

您也不需要将"hello world"转换为字符串-它已经是一个了。在

相关问题 更多 >

    热门问题