Tarrant
Tarrant

Reputation: 179

Get a letter out of a word

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 hangman

Upvotes: 0

Views: 3689

Answers (2)

Santiago Alessandri
Santiago Alessandri

Reputation: 6855

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.

Upvotes: 5

sahhhm
sahhhm

Reputation: 5365

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]

Upvotes: 6

Related Questions