Python Forum
'string index out of range' error when code replaces characters
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
'string index out of range' error when code replaces characters
#1
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
Reply
#2
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]
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  doing string split with 2 or more split characters Skaperen 22 2,317 Aug-13-2023, 01:57 AM
Last Post: Skaperen
  Error on import: SyntaxError: source code string cannot contain null bytes kirkwilliams2049 7 6,164 Aug-03-2023, 06:00 PM
Last Post: Gribouillis
  pyscript index error while calling input from html form pyscript_dude 2 938 May-21-2023, 08:17 AM
Last Post: snippsat
  Index error help MRsquared 1 738 May-15-2023, 03:28 PM
Last Post: buran
Thumbs Down I hate "List index out of range" Melen 20 3,157 May-14-2023, 06:43 AM
Last Post: deanhystad
  How do I check if the first X characters of a string are numbers? FirstBornAlbratross 6 1,427 Apr-12-2023, 10:39 AM
Last Post: jefsummers
Exclamation IndexError: Replacement index 2 out of range for positional args tuple - help? MrKnd94 2 5,958 Oct-14-2022, 09:57 PM
Last Post: MrKnd94
  IndexError: list index out of range dolac 4 1,843 Jul-25-2022, 03:42 PM
Last Post: deanhystad
  I'm getting a String index out of range error debian77 7 2,278 Jun-26-2022, 09:50 AM
Last Post: deanhystad
  IndexError: list index out of range Anldra12 2 1,408 May-03-2022, 01:39 PM
Last Post: Anldra12

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020