Index Error: string index out of range

时间:2016-06-10 16:13:48

标签: python

I am getting a

Traceback (most recent call last):   File "H:\Documents\game.py", line 73, in <module>
    if attemptThis[i] != target[i]: IndexError: string index out of range Press any key to continue . . .

error when I run this code.

#-----------------------------------------------------
# Python 'Evolution of Text' Program
# More programs at: usingpython.com/programs
#-----------------------------------------------------

possibleCharacters = string.ascii_uppercase + ' .!?;:='

target = """
       lMMMMMMMM                                                             .MMMM=         MMM                               MMM     
       lMM     MMl                                                          M=M   MMM       =MM                               MMM           
       lMM     M=.  MMM  M=M=   M=MM=MM    =M=====     M=MMMM=              M=M          MM=MMM==l  ==M===M=    MMM MMMM   =M=MM==MM   
       lMM     M=.  MMM==     MMM    .==  ==M....    =l=                      l===l=M.      MMM          .MMM   MMM=          MMM    
       lMM======    MMM       MM========   ......=ll   .....MMl             lll    =MM      =MM    l==....M=M   =MM           MMM 
       lM=          M=M         M=====M   =====M=M   =======MM               .M===MMM       MMM     =M====MMM   MMM           MMM      
"""
attemptThis = ''.join(random.choice(possibleCharacters) for i in range(len(target)))
attemptNext = ''

completed = False

generation = 0

while completed == False:
    print(attemptThis)
    attemptNext = ''
    completed = True
    for i in range(len(target)):
        if attemptThis[i] != target[i]:
            completed = False
            attemptNext += random.choice(possibleCharacters)
        else:
            attemptNext += target[i]
    if generation == 1000:
        break
    generation += 1
    attemptThis = attemptNext

I found this code here and modified it for my own uses. It was working before I added the exit clause

if generation == 1000:
    break

which I added because generating the ASCII was taking to long for my liking. I am using this as a title screen in a small project I am working on, so it is not crucial to get this fixed as I could always just go back to using a Print """Text Here""" command instead.

1 个答案:

答案 0 :(得分:3)

直接遍历集合而不是使用索引更加pythonic。由于我很好奇你的程序应该做什么,所以我重新编写了其他部分以使其运行。

import time, random, string
target = """  
    lMMMMMMMM                                                
    lMM     MMl                                              
    lMM     M=.  MMM  M=M=   M=MM=MM    =M=====     M=MMMM=  
    lMM     M=.  MMM==     MMM    .==  ==M....    =l=        
    lMM======    MMM       MM========   ......=ll   .....MMl 
    lM=          M=M         M=====M   =====M=M   =======MM  

     .MMMM=         MMM                               MMM    
    M=M   MMM       =MM                               MMM    
    M=M          MM=MMM==l  ==M===M=    MMM MMMM   =M=MM==MM 
      l===l=M.      MMM          .MMM   MMM=          MMM    
    lll    =MM      =MM    l==....M=M   =MM           MMM    
     .M===MMM       MMM     =M====MMM   MMM           MMM    
"""

chars = list(set(target + string.ascii_uppercase) - {'\n'})
attempt = ''.join('\n' for c in target)  
# First attempt is just a bunch of newlines. This makes the 
# text alignment correct after the first run through the loop

while target != attempt:
    attempt = ''.join(
        tc if tc == ac else random.choice(chars)
        for tc, ac in zip(target, attempt)
    )
    clearscreen = '\033c'  # linux terminal control character
    print(clearscreen + attempt)
    time.sleep(0.05)

这是预览的样子(链接到asciinema.org)

asciicast