0

In a game of Hangman, if the hidden word is hello and the player guesses l then I need to find the index of both locations.

Example:

word = "hello"
guess = "l"
position = word.index(guess)     #this helps me find the first one

I couldn't come up with any way to find the second. How am I able to do that?

Mete
  • 1
  • 1
  • 1
    also answered here http://stackoverflow.com/questions/11122291/python-find-char-in-string-can-i-get-all-indexes#11122355 – ziddarth Oct 11 '15 at 05:03

3 Answers3

2

Well, you could use enumerate and a list comprehension:

>>> s = "hello"
>>> indexes = [i for i, v in enumerate(s) if v == "l"]
>>> indexes
[2, 3]
Games Brainiac
  • 80,178
  • 33
  • 141
  • 199
0

Specifically for hangman:

>>> word = 'hello'
>>> guess = 'l'
>>> puzzle = ''.join(i if i == guess else '_' for i in word)
>>> print(puzzle)
__ll_
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
0

Another thing you could do, is preprocess the word and have the list of indexes already available in a map so you do not have to iterate trough the string all the time, only once.

word = "hello"

map = {}

for i, c in enumerate(word):
    if (c in map):
        map[c].append(i)
    else:
        map[c] = [i]

Than, check that the letter guessed is in map. If it is, the letter exists otherwise it does not.

Mate Hegedus
  • 2,887
  • 1
  • 19
  • 30