如何仅打印相应索引中单词的猜测字母?

时间:2013-03-16 19:58:06

标签: python python-2.7

我正在制作一个刽子手游戏,我需要制作一组下划线,这是一个字的长度,当用户正确猜出一个字母时,下划线组中的相应空格就成了正确的猜字母。我怎么能这样做?

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 个答案:

答案 0 :(得分: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_"