First part, to check if a letter or symbol is in a string:
if letter in string:
# do something
This will return true whenever "letter" in its exact form is present in the string. Different capitalisation, entered spaces or other differences will register as false, so you may want to clean up your user's input before checking it.
a = 'Factory'
False
'f' in a False
'F' in a
True
'F ' in a
False (Note the space after F)
Second, to find the indices of the letter(s) there are several ways:
mystring.index('letter')
# Returns the index of 'letter', but only the first one if there are more than one.
# Raises ValueError if not found.
Or we can use list comprehension to iterate through the string and return a list of all the indices where 'letter' is: (https://stackoverflow.com/a/32794963/8812091)
indices = [index for index, char in enumerate(mystring)
if char == 'letter']
# Go over the string letter by letter and add the letter position
# if it matches our guessed letter.
Third, to update the string with found letters we iterate over the '----' string and put in the guessed letter at the correct positions. See below.
Putting it into your script:
word_guessed = input("Enter a Word to be guessed: ")
type(len(word_guessed))
print(len(word_guessed)* '-')
current_guess = str('-' * len(word_guessed))
# The current state of the guessed word fixed as a variable for updating
# and printing.
guess_letter = 'F'
# Fixed input letter for testing with the word "Factory".
if guess_letter in word_guessed:
letter_indices = [index for index, char in enumerate(word_guessed) if char == guess_letter]
# Or if you want to show only one (the first) of the guessed letters:
# letter_indices = word_guessed.index(guess_letter)
print("Correct Guess, Guess again: ")
print("The Letter is located:", letter_indices)
# Now update the current guess to include the new letters.
current_guess = ''.join(guess_letter if index in letter_indices
else char for index, char in enumerate(current_guess))
# We can't change strings, so we build a new one by iterating over the current guess.
# Put in the guess letter for the index positons where it should be, otherwise keep
# the string as is. ''.join() is an efficient way of combining lots of strings.
print(current_guess)
Enter a Word to be guessed: Factory
"-------" (Added " to avoid SO autoformatting)
Correct Guess, Guess again:
The Letter is located: [0]
F------