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)
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:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.