I am trying to create a function that takes a word housed in a variable and modifies it according to the letter that I am entering until the variable does not contain any '_'. The code does not give any type of error, it simply does not work even though if I try line by line if it fulfills its function. any suggestion?
def reveal_word():
string = '____'
word = 'cat'
while '_' in string:
letter = input('Enter your letter: ')
for index in string:
index = word.find(letter)
string[index].replace('_',letter)
return string
print(reveal_word())
CodePudding user response:
def reveal_word():
word = "capybara"
string = "_" * len(word)
while "_" in string:
print(string)
char = input("Enter your letter: ")[0] # [0] to get the first letter
idx = word.find(char)
if idx != -1:
word = word[:idx] "_" word[idx 1 :]
string = string[:idx] char string[idx 1 :]
return string
print(reveal_word())
CodePudding user response:
Here is a somewhat simpler solution. It uses a list of characters in the word and drops matched characters from that list until the list is empty:
def reveal_word():
word = 'cat'
string = list(word)
while string:
letter = input('Enter your letter: ')
if letter in string:
string = list(filter(lambda val: val != letter, string))
return word
print(reveal_word())
CodePudding user response:
Here's a sample with a slightly different twist. In this example if a character exists more than once in the word to guess, every location will be updated with that character.
def reveal_word():
string = '________'
word = 'Hercules'
while '_' in string:
letter = input('Enter your letter: ')
for index in range(0, len(string)):
if (string[index] == '_'):
if (word[index] == letter):
temp = list(string)
temp[index] = letter
string = "".join(temp)
print('String: ', string)
return string
print(reveal_word())
Here is some terminal output.
Enter your letter: e
String: _e____e_
Enter your letter: H
String: He____e_
Enter your letter: r
String: Her___e_
Enter your letter: c
String: Herc__e_
Enter your letter: u
String: Hercu_e_
Enter your letter: l
String: Hercule_
Enter your letter: s
String: Hercules
Hercules
Just another take on the puzzle.
Regards.