Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
505 views
in Technique[技术] by (71.8m points)

python - How can I print only guessed letter from a word in their corresponding indicies?

I am making a hangman game and I need to have to make a set of underscores that is the length of the word and when the user correctly guess a letter the corresponding space in the set of underscores becomes the correctly guess letter. How can I do this?

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?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could do something like this:

guess = "sol"
word = "stackoverflow"
hint = [l if l in guess else "_" for l in word]
print "".join(hint)

Here, guess is a string (or a list, or a set) holding all the letters the user has guessed so far, and word, obviously, is the word to guess. hint then is a list holding for each letter l in the word either that letter, if it is in the set of guessed letters, or an underscore. Finally, that hint is joined to a string and printed.

Output for this example would be "s____o____lo_".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...