0

I am trying to create a word guess game whereby I replace correct letter guesses in a hidden word. I can't see to figure out why when I use the insert method my code will not replace the list with the correct letter. Sorry.. fairly new to coding and python.

I have tried a counted loop, converting the user input to a list.

word = 'tuner'
word = list(word)
dash= []

for i in range(len(word)) :
    dash.append('_')
guess = input('Please enter a letter to guess if it is in the word : ')

for i in range(len(word)):
    if word[i]== guess :
        dash.insert(i,guess)      
print (dash)

I expect to see the list printed on the screen.. with the correct guessed letter replacing the dash... however the list appears to be appended with the correct letter and not replacing the dash at the appropriate index. ie... _ _ _ e_ _

Rocco32
  • 9
  • 2

3 Answers3

2

insert insert an item to the list, if you want to replace it use dash[i] = guess

1

A simple fix; don't insert a new character to the list, but instead change the existing element(s):

for i in range(len(word)):
    if word[i]== guess :
        dash[i] = guess  # FIXED     
print (dash)
ruohola
  • 21,987
  • 6
  • 62
  • 97
1

just a few changes to your code :)

for i in range(len(word)):
    if word[i] == guess:
        dash[i] = guess

print(' '.join(dash))
kederrac
  • 16,819
  • 6
  • 32
  • 55