Python Forum

Full Version: Replacing letters on a string via location
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hey guys,

I was wondering if there is a way to replace a letter on a string via location, and if i can do it if there are multiple locations.
I'm working on a hangman simple python code

def game_start():
    print("Hey there, would you like to play the game? (Y/N)")
    user_answer = input("(Y/N)>>> ")
    if user_answer.lower() == "y":
        print("Thinking on a word...")
        word_random = random.choice(list_list)
        word_enumerate = list(enumerate(word_random))
        word_simulator = "_ " * len(word_random)
        word_trys = 0
        word_max = len(word_random) * 3
        # time.sleep(2)
        while word_trys < word_max:
            print("Enter letter to guess: ")
            print(word_random)
            user_answer = input(">>> ")
            if len(user_answer.lower()) > 1 or user_answer.isdigit() == True:
                print("Invalid answer")
                continue;
            else:
                word_integers = [x for x, y in word_enumerate if y == user_answer]
This is my main function,
i'm stuck on the last row, i have for example:

word_random = india
user_answer = "i"
word_integers = [0, 4]
word_simulator = _ _ _ _ _ # This is what displays each guess for the user, which i want to convert next round to i _ _ i _
thanks :)
Would have to change string to a list.
string = 'india'
visible = '_' * len(string)
print(' '.join(list(visible)))

def guess(letter, string, visible):
    visible = list(visible)
    for enum, c in enumerate(string):
        if c == letter:
            visible[enum] = c

    return ''.join(visible)

visible = guess('i', string, visible)
print(' '.join(list(visible)))
or keep visible word as a list.
Keep in mind that as strings are immutable, to replace characters you will need to rebuild the string with the replacements you want.

In that case, you might just as well rebuild word_simulator each time based on user guesses so far:
word_simulator = ''.join([c if c in user_guesses else '_' for c in word_random])
where user_guesses holds a copy of all of the unique guesses so far.