![](/img/trans.png)
[英]Hangman with dashes in Python - can't figure out why the code is not working
[英]May someone help me figure out how to update my dashes on my python hangman code
我应该能够更新这些破折号,这样当有人输入“a”时,破折号看起来像 a---a-。 如果用户猜到字母“l”,破折号看起来像 a---al。
magic_word = "animal"
dashes = "--------"
def get_guess()
while True:
print dashes
guess = str(input("Guess a letter: "))
if len(guess)>1:
print "Too long"
continue
elif not guess.islower():
print "Your guess must be one lowercase letter"
continue
if guess in magic_word :
print "That is in the word"
continue
else:
print "That is not in the word"
continue
return guess
break
get_guess()
您想使用不同的方法来查看猜测是否在魔术字中。
一种这样的方法是遍历字符串,只要在魔术字中找到猜测,就更新破折号字符串中的相应空格:
for x in range(len(magic_word)):
if guess == magic_word[x]:
dashes[x] = guess
哪个会为你更新破折号
您应该使用“index()”方法来查找字符的索引,然后使用“replace()”方法用该单词替换破折号。
indexOfGuessChar = magic_word.index(guess)
dashes = dashes.replace(dashes[indexOfGuessChar], guess)
像这样的事情就可以解决问题,只需将这些功能投入使用并使用它即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.