Forum Archive

Is there a Command for matching letters in a word

Bjucha

Hello

Im doing a simple text based hangman game and I was woundering if there is
A command for telling the user witch letters in a Word is matching.
So if the Word is: car and user guesses: cat
I would like to tell the user that the c and a is right But not the t

Greatful for any help

mikael

There is probably something more clever in Python, but here's the simple way:

word = 'cat'
guess = 'car'

match = ''

for index in range(len(word)):
  match += word[index] if word[index] == guess[index] else '*'

print(match)

There's many examples of hangman in Python available, just Google it.

Bjucha

Thanks!!! gonna try it

ccc

`print(''.join(x for x in guess if x in word))

Bjucha

it worked. However if the word is too short or too long it will create a "string index out of range error" I have tried to fix it but no luck

This is the where the error is produced:
match += word[index] if word[index] == guess[index] else '*'

Greatful for any help

Bjucha

If I use:
If len(guess) > len(word):
Print("Too many letters") it works
But not for

If len(guess) < len(word):
Print("Too few letters") it does not work it will produce the sting index out of range error

ccc
word = 'catatonic'
guess = 'cat'

def matching_letters(word, guess):
    return ''.join(c if i < len(guess) and c == guess[i] else '*'
                   for i, c in enumerate(word))

print(matching_letters(word, guess))
print(matching_letters(guess, word))

Of course this does not happen in real hangman because you give the user the correct number of blanks.

Bjucha

Thx
Gonna try it in my code
Really appriciate it