what x.replace(a, b)
does is replace any occurrences of the value a
in x
with b
so answer.replace(answer[location], userInput)
just replaces all *
with the value of userInput
because answer[location]
is *
. In other words, it's not possible to specify the index of what you want to replace like that.
So instead of:
answer = answer.replace(answer[location],userInput)
do
answer = answer[:location] + userInput + answer[location + 1:]
UPDATE:
The rest of the logic was also flawed, so this will work:
userInput = "i"
word = "university"
answer = "*" * len(word)
for location, letter in enumerate(word):
if letter == userInput:
answer = answer[:location] + userInput + answer[location + 1:]
This also contains the suggestion to use enumerate()
by SethMMorton, which turns out to be unavoidable :)
enumerate('abc')
will yield [(0, 'a'), (1, 'b'), (2, 'c')]
, which means you won't need to use find
as you'll already have the location (index) of the letter available right away.