0

I'm working on a hangman game in Python. My "answer" list contains all the letters of the word in order, the "work" list starts off with dashes for each letter, which are then populated with correct letters.

When using index(), it only returns the lowest position in the list that the value appears. However, I need a way to make all instances of the value be returned (otherwise repeating letters aren't getting filled in).

I'm new to Python, so I'm not sure if some kind of loop is best, or if there is a different function to get the result I'm looking for. I've looked at enumerate() but I'm not sure how this would work in this instance.

if guess in word:
    print("Correct!")

    for i in range(count):
        work[answer.index(guess)] = [guess]

    print(work)
petezurich
  • 9,280
  • 9
  • 43
  • 57
  • can you give an example input and desired output? I'm not sure I fully understand what you're trying to do. – David Culbreth Oct 18 '18 at 15:36
  • So, currently, if the generated word was "hello", answer would look like ["h", "e", "l", "l", "o"] and work would look like ["_", "_", "_," "_", "_"]. As it stands, if the user guessed "l", the index would return 3, and the third item in the work list would be populated with "l". However, the second "l" is never given, so won't be populated – Rebecca Procter Oct 18 '18 at 15:40
  • index method can be given an offset to start the search see `help(str.index)`. Use the last match position+1 to advance. – progmatico Oct 18 '18 at 15:45

1 Answers1

1

As you mentioned the problem is that index returns only the first occurrence of the character in the string. In order to solve your problem you need to iterate over answer and get the indices of the characters equal to guess, something like this (using enumerate):

guess = 'l'
word = "hello"
work = [""] * len(word)
answer = list(word)

if guess in word:
    print("Correct!")
    for i, c in enumerate(answer):
        if c == guess:
            work[i] = guess
    print(work)

Output

Correct!
['', '', 'l', 'l', '']

Note that work is slightly different from what you put on the comments.

Further:

  1. How to find all occurrences of an element in a list?
Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76