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
Post a Comment