'How to insert a character into a string at a certain index? [duplicate]

Is there a way to insert a character into a string at a certain index? I am making a hangman game, and as players guess the letters, the "_" or blanks become filled with letters.

import random
import sys

forever = True
lives = 7
chosen_word = "none"
playing = True
length = "none"
letter = "none"
guessed = 0
user_input = False

words = [
    "snag", "jungle", "important", "peasant", "baggage", "hail", "clog", "pizza", "sauce", "password", "scream",
    "newsletter", "bookend", "pro", "dripping", "pharmacist", "lie", "catalog", "ringleader", "husband", "laser",
    "diagonal", "comfy", "myth", "dorsal", "biscuit", "hydrogen", "macaroni", "rubber", "darkness", "yolk", "exercise",
    "vegetarian", "shrew", "chestnut", "ditch", "wobble", "glitter", "neighborhood", "dizzy", "fireside", "retail",
    "drawback", "logo", "fabric", "mirror", "barber", "jazz", "migrate", "drought", "commercial", "dashboard",
    "bargain",
    "double", "download", "professor", "landscape", "ski", "goggles", "vitamin",
]

print("Let's play Hangman! Guess the letters!")
chosen_word = (random.choice(words))
length = len(chosen_word)

while playing:
    print("_" * length)
    letter = (input(f"You have {lives} guesses left."))
    if letter in chosen_word:
        location = chosen_word.find(letter)
        insert_word = list(chosen_word)
        
        print(insert_word)
        print("Great Job! You got a letter!")
    else:
        print("That letter is not in the word.")
    lives -= 1

while forever:
    if lives <= 0:
        playing = False
        print("You lost. Good game.")
        user_input = (input("Would you like to play again?"))
        if user_input == "False":
            print("Good bye.")
            sys.exit()
        elif user_input == "True":
            playing = True
            print("Let's play Hangman again! Guess the letters!")

I have been able to locate the index where the character is supposed to go in, but I have no idea how to make the character replace the "_" already in that spot. I am currently trying to convert the word into a list first and insert the character in there.



Solution 1:[1]

two things to keep in mind:

first- you need to keep asking for input as long as player has guesses remaining or guessed the right letter.

second - you need to initialize hangman before the loop as a list as that is the only way you will keep track of players guess.

chosen_word = (random.choice(words))
length = len(chosen_word)
hangman = ['_' for i in range(length)]

while playing:

    print("guess a letter")
    letter = input()
    if letter in chosen_word:
        pos = chosen_word.index(letter)
        chosen_word = list(chosen_word)
        chosen_word[pos] = '-'
        chosen_word = ''.join(chosen_word)
        hangman[pos] = letter
        print(hangman)

    else:
        lives -= 1 
        if lives == 0:
            print("you lose")
            playing = False
            break
    
    if '_' not in hangman:
        print("winner")
        playing = False
      

you are putting the input for guessing a letter outside the loop while playing is True. you need to keep it inside the conditional loop. As for inserting a character at an index for a string you just have to turn it into a list and then revert it back into a string using the .join method

Solution 2:[2]

Like @ddejohn said, convert it into a list first and then join the list back together after the insertion.

def insert_into_string(string, index, character):
    string_list = list(string)
    string_list[index] = character
    return "".join(string_list)

Example usage:

>>> insert_into_string("H_llo world!", 1, "e")
'Hello world!'

Solution 3:[3]

Try to initialize a list using list comprehension, like this:

secret_word = ['_' for l in word_chosen]

Then use the find method at the word_choosen to find the position, and then use that position to replace the '_' in the secret_word list.

Here is a example code:

def start_game():
    secret_word = 'programming'
    guessed_word = ['_' for w in secret_word]
    print(guessed_word)
   
    while True:
        guessed_letter = input('Guess a letter: ').lower()

        found_at = 0
        
        while secret_word.find(guessed_letter, found_at) > -1 and guessed_letter is not '':
            found_at = secret_word.find(guessed_letter, found_at)
            guessed_word[found_at] = guessed_letter
            found_at += 1

        # check for win condition
        if '_' not in guessed_word:
            print('Congratulation! You\'ve won!')
            break

        if guessed_letter == "exit":
            print("Thanks for playing :D")
            break

        print(guessed_word)
    
if __name__ == '__main__':
    start_game()

Solution 4:[4]

You can replace character from list then use join method to create a string

print ("WELCOME TO HANGMAN")
chosen_word = (random.choice(words))
chosen_word = chosen_word .upper()
word_ = '_'*len(chosen_word )
print (word_)   
for chance in range (lives):
        letter = (input(f"You have {lives-chance} guesses left."))
        letter = letter .upper()
        word_ = list(word_)
        UI_pos= [pos for pos, char in enumerate(chosen_word ) if char == letter ]
         for pos in UI_pos:
            word_[pos] = letter
        word_ = ''.join(word_)
        print(word_)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3
Solution 4 im_vutu