Skip to main content
 首页 » 编程设计

python之在 Python 中遍历一个字符串

2025年05月04日22lyj

我想写一个脚本,一个一个地输入字符串

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) 

错误是:列表索引超出范围 我该如何解决?

请您参考如下方法:

列表的长度是列表中元素的数量。但是,列表从索引 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" 转换为字符串 - 它已经是一个字符串了。