Home > Net >  how to replace element in list python 3
how to replace element in list python 3

Time:05-19

I have a list (display) that I need to update as the user does their input. So, if the user input the letter A, I need the letter A to replace an element in the new list called display. I might not be writing this code correctly, but I'm stuck at the code below. I'm not sure how I can write the code to replace the element in the list called display. Any help or guidance would be much appreciated. TIA

import random
name_list = ["daniel", "babs", "cal"]
chosen_word = random.choice(name_list)

display = []
guess = input("Guess a letter: ").lower()

for numChar in range(len(chosen_word)):
    display  = "_"

for letter in chosen_word:
    if letter == guess:

EXPECTED OUTPUT:

If the user input was "a" and the chosen_word is babs, since it has an "a" in it, I need it to replace the list ('', '', '', '') with the corresponding letter. ('', 'a', '', '_')

CodePudding user response:

You're trying to make hangman, aren't you? Try this:

import random
name_list = ["daniel", "babs", "cal"]
chosen_word = random.choice(name_list)

display = []
guess = input("Guess a letter: ").lower()

if guess == chosen_word:
    display = list(chosen_word)
else
    for numChar in range(len(chosen_word)):
        if numChar == guess[0]:
            display.append(numChar)
        else
            display.append("_")

CodePudding user response:

import random
name_list = ["daniel", "babs", "cal"]
chosen_word = random.choice(name_list)

display = []
guess = input("Guess a letter: ").lower()

display[:] = [guess if x == guess else "_" for x in chosen_word]

CodePudding user response:

Use enumerate to get each letter as well as its index:

import random

name_list = ["daniel", "babs", "cal"]
chosen_word = list(random.choice(name_list))
display = ["_" for _ in chosen_word]

while display != chosen_word:
    print(display)
    guess = input("Guess a letter: ").lower()
    for i, letter in enumerate(chosen_word):
        if letter == guess:
            display[i] = letter
  • Related