Python Forum

Full Version: 'string index out of range' error when code replaces characters
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
This hangman game isn't entirely finished as I'm still working on it, however i came across this error which occurs very often if i get all my guesses correct. When i run it and guess a number of guesses it will sometimes not print the correct amount of left gaps after the letter or the error:

Traceback (most recent call last):

 File "C:\Users\Gaming\Desktop\Hangman.py", line 110, in <module>

   display(Hangman,randomWord,wrongLetters,correctLetters)

 File "C:\Users\Gaming\Desktop\Hangman.py", line 73, in display

   blanks = secretWord[i] + blanks[:i]  + blanks[i+1] #blanks[i+1] adding '-' from the old 'blanks'
IndexError: string index out of range

will come up and sometimes both errors will happen follow one after another.

Can someone tell me how to fix this error and why it happens?



import random

Hangman = ['''

   +---+
   |   |
       |
       |
       |
       |
 =========''', '''

   +---+
   |   |
   O   |
       |
       |
       |
 =========''', '''

   +---+
   |   |
   O   |
   |   |
       |
       |
 =========''', '''

   +---+
   |   |
   O   |
  /|   |
       |
       |
 =========''', '''

   +---+
   |   |
   O   |
  /|\  |
       |
       |
 =========''', '''

   +---+
   |   |
   O   |
  /|\  |
  /    |
       |
 =========''', '''

   +---+
   |   |
   O   |
  /|\  |
  / \  |
       |
 =========''']

words = 'ant baboon badger bat bear beaver camel cat clam cobra cougar coyote crow deer dog donkey duck eagle ferret fox frog goat goose hawk lion lizard llama mole monkey moose mouse mule newt otter owl panda parrot pigeon python rabbit ram rat raven rhino salmon seal shark sheep skunk sloth snake spider stork swan tiger toad trout turkey turtle weasel whale wolf wombat zebra'.split()

def GetRandomWord(word):
    chosenWord = random.choice(word)
    return chosenWord


def display(hangmanPic,secretWord,numWrongLetters,correctLetters):
    blanks = '-'*len(secretWord)

    for i in range(len(secretWord)):#repleaces blank letters with correct letters
        if secretWord[i] in correctLetters:
            blanks = secretWord[i] + blanks[:i]  + blanks[i+1] #blanks[i+1] adding '-' from the old 'blanks'

    print("Missing Letters:")        
    for letter in blanks:
        print(letter,end='')
    print(hangmanPic[numWrongLetters])



def getGuess(alreadyGuessed):
    while True:
        print("Guess Letter:")
        guess = input()
        guess = guess.lower()
        if len(guess) != 1:
            print("Please enter only 1 letter.")
        elif guess in alreadyGuessed:
            print("Letter is already guessed.")
        elif guess.isdigit():
            print("Please enter a letter not integer.")
        else:
            return guess

def playAgain():
    print("Do you want to play again?") 
    pass



print("H A N G M A N")
correctLetters = ''
guessedLetters = ''
wrongLetters = 0
randomWord = GetRandomWord(words)
gameDone = False

while True:
    display(Hangman,randomWord,wrongLetters,correctLetters)
    guess = getGuess(correctLetters + guessedLetters)

    if guess in randomWord:
        correctLetters += guess
        foundAllLetters = True
        for i in range(len(randomWord)):
            if randomWord[i] not in correctLetters:
                foundAllLetters = False
                break
        if randomWord[i] in correctLetters:
            foundAllLetters = True
            print("Well Done You found what the missing word is!")
            gameDone = True

    else:
        wrongLetters +=1
        guessedLetters += guess
Don't worry guys i found the problem
i need to change 'blanks = '-'*len(secretWord)' to blanks = ['-']*len(secretWord)
and then change 'blanks = secretWord[i] + blanks[:i] + blanks[i+1]' to blanks[i] = secretWord[i]