0

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.

mx0
  • 6,445
  • 12
  • 49
  • 54
Sam Cao
  • 1
  • 2
  • Strings are immutable, meaning you can't change strings, you can only transform them. You'll need to rebuild the string. One way would you could do that would be to convert the string to a list (which *is* mutable), change the character at that index, then join back into a string with `"".join(list_of_chars)`. – ddejohn Apr 01 '22 at 04:30
  • It looks like he means "replace" rather than "insert," since he wants to turn the underscores into letters. Still, those answers should be helpful since it is only a slight difference. – eshapiro42 Apr 01 '22 at 04:47

4 Answers4

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

0

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!'
eshapiro42
  • 186
  • 1
  • 2
  • 14
-1

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()
-1

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_)
im_vutu
  • 412
  • 2
  • 9