How would I find all occurances of the letter 'e' for example in a list of the split word elephant?
I've tried using letterlist.index('e') for example but index only returns the first occurance of e.

This is to be used in a hangman game, and the game needs to display all the characters that have been guessed amongst a list of "-" dashes
So how would I replace "-" with the correctly guessed letter.

Thanks!

Dani AI

Generated

wanted to reveal every occurrence of a guessed letter in a hangman word. ’s list-comprehension is a neat one-shot way to build a display, and is right — when players guess progressively you typically iterate the secret word and update a mutable mask. Two clear, safe patterns follow.

A simple, idiomatic approach is to keep a list of characters for the mask and update positions with enumerate so you preserve original casing and only change the matching indices:

secret = "elephant"
mask = ['-'] * len(secret)
guess = 'e'

for i, ch in enumerate(secret):
    if ch.lower() == guess.lower():
        mask[i] = secret[i]   # keeps original case

print(''.join(mask))  # e-e-----

If you prefer locating occurrences directly, use str.find with a start position to loop through all matches (useful when you want index-based logic):

start = 0
while True:
    idx = secret.find(guess, start)
    if idx == -1:
        break
    mask[idx] = secret[idx]
    start = idx + 1

Notes and pitfalls: keep the mask as a list (strings are immutable), compare lowercased values for case-insensitive matching but write back the original character to preserve case, and track previously guessed letters with a set to avoid reprocessing. For typical hangman words both approaches are O(n) per guess and fine; enumerate is simplest and clearest for progressive reveals.

Recommended Answers

All 2 Replies

print(['e' if letter == 'e' else '-' for letter in 'elephant'])
'''Output:
['e', '-', 'e', '-', '-', '-', '-', '-']
'''

Your code is not tested to work and does not belong to code snippets.

So how would I replace "-" with the correctly guessed letter

There are 3 containers here, the "secret word", the hangman list, and the letter quessed. You would iterate over the "secret word" and compare letters. If the letters match then replace the "-" at the same postion in the hangman list..

for position in range(len(secret_word)):
    letter = secret_word[position]
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.