Home > database >  How to replace more than one occurrence of a letter in list?
How to replace more than one occurrence of a letter in list?

Time:03-26

I'm trying to make a Hangman game. To start the verification of the word, I created a list with all the letters in certain word and another list with the '-' symbol for each letter in word. While verifying if the input letter is in the word, this only works when the letter appears only one time. When the letter appears two or more times, it does not work.

def game():
    word = list(chosen_word())
    word_to_verify = ['-' for c in word]
    while word != word_to_verify: 
        print('Welcome to the Hangman game! \n',*word_to_verify)
        letter_input = input('\nInsert a letter: ').upper()
        os.system ("clear")
        for letter in word:
            if letter_input == letter :
                word_to_verify[word.index(letter)] = letter
            else: 
                pass

The line word_to_verify[word.index(letter)] = letter does not work correctly.

Word: A P P L I C A T I O N

Output: A P _ L I C _ T _ O N

Expected output: A P P L I C A T I O N`

CodePudding user response:

In this loop:

        for letter in word:
            if letter_input == letter :
                word_to_verify[word.index(letter)] = letter

word.index(letter) will always return the first index of letter in word, so if there are multiple occurrences of letter, you'll be setting that first index twice in word_to_verify. That's why after the loop is finished, the first occurrence has been replaced, but the other(s) remain blank.

If you use enumerate in your iteration over word, you'll get the index of each individual occurrence of letter, and can use that index in word_to_verify:

        for i, letter in enumerate(word):
            if letter_input == letter :
                word_to_verify[i] = letter

Note that else: pass does nothing and you can just remove it.

CodePudding user response:

Other answers are correct, but if you want to do it the standard way you should read the following.


You have to replace it with the str.replace method, specifying the third argument:

myString = myString.replace('old', 'new', number_of_occurrences_to_replace)

CodePudding user response:

word.index() always returns the first occurrence of the letter in the word.

It is not a drop-in replacement for indexing.

You should use brackets to index into the list instead:

for index, letter in enumerate(word):
    if letter_input == letter:
        word_to_verify[index] = letter
  • Related