如何仅打印猜中的字母及其对应的索引?
我正在制作一个猜单词的游戏(叫做“吊死鬼”),我需要创建一串下划线,长度和单词一样。当用户正确猜到一个字母时,这串下划线中对应的位置就会变成用户猜对的字母。我该怎么做呢?
userGuess = raw_input('Enter a letter or the word: ')
guessed = ''
def getWordList:
#just getting a word from a tct file and returning a random word from it
return word
def askForInput(userGuess):
xx = str(userGuess)
yy = xx.lower()
return yy
def showWord:
print'_ ' * len(word) #I know this part is wrong if I want to add the letters
print 'Guesses: %s' %guessed
if askForInput(userGuess) in word:
print 'There are %ss' %askForInput(userGuess).upper()
#now what can I do with showWord or how can I fix showWord?
1 个回答
2
你可以这样做:
guess = "sol"
word = "stackoverflow"
hint = [l if l in guess else "_" for l in word]
print "".join(hint)
在这里,guess
是一个字符串(或者列表,或者集合),里面存放着用户到目前为止猜的所有字母。而 word
显然就是要猜的那个单词。接着,hint
是一个列表,里面为单词中的每个字母 l
提供信息:如果这个字母在用户猜的字母中,就显示这个字母;如果没有,就用下划线代替。最后,这个提示信息会被连接成一个字符串并打印出来。
这个例子的输出结果会是 "s____o____lo_"
。