Hangman in Python - Replace multiple characters in single string based on index python -


trying create game called hangman in python. i've come long way, 'core' functionality failing me.

i've edited out parts irrelevant question.

here comes:

    picked = ['yaaayyy']     length = len(picked)     dashed = "-" * length      guessed = picked.replace(picked, dashed)      while tries != -1:         input = raw_input("try letter: ")         if input in picked:             print "correct letter!"             found = [i i, x in enumerate(picked) if x == input]             item in found:                 guessed = guessed[:item] + input + guessed[i+1:]             print guessed 

upon calling script, python creates variable named guessed containing 7 dashes ------- asks user letter , if letter correct, replace - correct letter. not keeping previous letters.

the word guessed yaaayyy

output of code:

word 7 characters: ------- try letter: correct letter! -aaa try letter: y correct letter! yyyy 

goal:

word 7 characters: ------- try letter: correct letter! -aaa--- try letter: y correct letter! yaaayyy 

this code seems wrong:

found = [i i, x in enumerate(picked) if x == input] item in found:     guessed = guessed[:item] + input + guessed[i+1:] 

that last line should be:

guessed = guessed[:item] + input + guessed[item+1:] 

edit

this seems simpler me:

for i, x in enumerate(picked):     if x == input:         guessed = guessed[:i] + input + guessed[i+1:] 

edit 2

i'm not sure if clearer or not, it's little more efficient:

guessed = ''.join(x if picked[i] == input else c i, c in enumerate(guessed)) 

Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -