Tyler Mathis Tyler Mathis - 1 year ago 35
Python Question

Storing location of characters in string

I am writing a Hangman program during my free time at school, as an entry level project for Python, and I have finally run into an obstacle.

What I want to do:

So far I have printed a board to the size of the word inputted, and I can decide if the guesses are correct or not, with a working score. Now I need to take a correct guess, and change the correct underscores in str(board) into their actual letter. To do this I wanted to grab the locations of the character guessed (if correct) in the FULL CORRECT WORD and then simply change that position in board into the correct letter. Sorry for the wordyness! Here is my code.

print("Welcome to Tyler's Hangman game!!!! Player one, input a word for player two to guess, lowercase!\n")

playAgain = True
guessing = True
#assure game starts in the True state

while playAgain == True:

word = str(raw_input())
wordLength = int(len(word))
board = "_ " * wordLength
lives = 9
#initialize/reset variables on a new play

while guessing == True:

print("\n" * 15)
print("Now its player two's turn to make a guess! You have 9 lives! Only one letter at a time, lowercase!\n")
print(board + "Lives: " + str(lives) + "\n")
#print board + lives

guess = str(raw_input())

if guess in word:

score -= 1
#check guess and change board

The statement starting with if guess in word: is where things start to get confusing for me. Thanks!!

Snippet I'm confused with

if guess in word:

Answer Source

I'm going to propose an alternative solution to your real problem. Mutating strings is not very idiomatic in Python and is prone to errors. My approach instead will be to keep track of which letters have been guessed and then compute the board state from that and the actual answer.

answer = 'hello world'
guessed = ['a', 'e', 'm', 'r']
def compute_board(answer, guessed):
    return ''.join(c if c == ' ' or c in guessed else '_' for c in answer)
compute_board(answer, guessed) # gives _e___ __r__

Now you can easily get the number of guesses from the length of the guessed list, you can check for repeated guesses easily by checking if their guess is already in the list, and you can add guesses easily by just adding them to the end of the list.