开发者

Get a letter out of a word

开发者 https://www.devze.com 2023-02-03 23:37 出处:网络
a = [\'cat\',\'dog\'] random.choice(a) How can I choose a random word, and pull out a letter? I\'ve searched and experimented and whatnot but can\'t find an answer.
a = ['cat','dog']

random.choice(a)

How can I choose a random word, and pull out a letter? I've searched and experimented and whatnot but can't find an answer. thanks.

I don't want a random letter, for instances I want it to choose a word, cat. then I want someone to guess either c a or t. Kind of like ha开发者_如何学Gongman


If you want to choose a random character from the randomly selected word:

random.choice(random.choice(a))

Or, if you want the first letter (for example) of the randomly chosen word:

random.choice(a)[0]


First to pick the word, you use what you published.Then you can make a set from the word to get the set of letters it contains. And you can use it to check whether the input is part of the word and keep the remaining letters. You can do:

chosen_word = random.choice(['cat', 'dog'])
letters_set = set(chosen_word)
while len(letters_set) > 0:
    letter = raw_input() #make controls on this.
    if letter in letters_set:
        letters_set.remove(letter)
        print "Good!"
        print ''.join(map(lambda c: c in letters_set and '_' or c, chosen_word))
    else:
        print "Bad Bad, try again!"

Hope it is useful.

0

精彩评论

暂无评论...
验证码 换一张
取 消