2
votes

How do I make my python hangman game replace the underscores in the variable blanks with the correct letter if it is guessed.

I have the correct if statement but I am not sure how to get the letters replaced.

This is what I tried:

def main()
    if choice in correctAnswer:
        print("\nCorrect!\n------...\n")

        index = 0
        while index < len(correctAnswer):
            index = correctAnswer.find(choice, index)
            if index == -1:
                break
            print(index)
            index += 1

        used.append(choice)

        places = []
        place=correctAnswer.index(choice)
        blanks[place]=choice
        blanks=''.join(blanks)
main()

That gives me typeError: TypeError: 'str' object does not support item assignment

Any ideas on how to do this?

Thanks

UPDATE:

blanks = list(makeBoard(correctAnswer))

print (correctAnswer)

def main():
    used = []
    print(blanks)
    choice = input("\nEnter a letter:")

    if len(choice) == 1 and special_match(choice) == True:

        if choice in correctAnswer:
            print("\nCorrect!\n--------------------------------------------------------------------\n")

            index = 0
            while index < len(correctAnswer):
                index = correctAnswer.find(choice, index)
                if index == -1:
                    break
                print(index)
                index += 1

            used.append(choice)

            [choice if letter == choice else blank for blank, letter in zip(blanks, correctAnswer)]

            main()
3
can you fix indentation i can't fully understand your code - Sardorbek Imomaliev

3 Answers

5
votes

You'd be better off working with a list because strings are immutable

>>> blanks = list('_______')
>>> answer = 'hangman'
>>> guess = 'g'

>>> blanks[answer.index(guess)] = guess
>>> blanks
['_', '_', '_', 'g', '_', '_', '_']

So this keeps blanks mutable so you can replace elements at will. Then when you want to display this to the user as a string

>>> ''.join(blanks)
'___g___'

A list comprehension could handle repeated letters

>>> [guess if letter == guess else blank for blank, letter in zip(blanks, answer)]
['_', 'a', '_', '_', '_', 'a', '_']

Edit
Please see the following quick demo, note you should add handling of incorrect guesses

answer = 'hangman'
blanks = list('_'*len(answer))
for guess in set('hangman'):
    blanks = [guess if letter == guess else blank for blank, letter in zip(blanks, answer)]
    print(''.join(blanks))

Output

h______
h__g___
h__gm__
ha_gma_
hangman
0
votes

Here's what I did:

if guess_input in current_word:
    cpos = 0
    for letter in current_word:
        if letter == guess_input:
            guess = guess[:cpos] + guess[cpos].replace("*",guess_input) + guess[cpos + 1:]
        cpos += 1

Guess is equal to "*" * len(current_word)

In your case, you would use "_".

This works with repeated letters.

0
votes

i recently tried this as a hobby project.

i used regex to do the job.

inputRegex = re.compile(r'^\w{1}$')  #regex for checking if only one alphabet has been input

thisGuess = self.myGuess.text().upper()
check = re.findall(thisGuess, self.qDisp)
# now if there is match will be non zero
quest = list(self.qDisp) # conv the blank word display into list for easy replace
#find the position of the guess in the string
for check in re.finditer(thisGuess, self.quest):
   i = check.start() #this gives the starting position of the match
   quest[i] = thisGuess  # 


self.qDisp = "".join(quest) #to join the list into string from list created above loop