I am creating a game of hangman in python 3 and all seems to be working well apart from one part of the game. Take for example, the word 'hello'. Hello contains two 'l's. My game does not recognise that you can have more than one occurrence of a letter in a word and therefore does not update the game as it should. Here is how the program runs -
When entering 'L'
The number of times L occured was 2
('WORD:', 'HEL*O', '; you have ', 10, 'lives left')
Please input a letter:
def updateGame (x, charStr) :
occ = x['secWord'].count(charStr)
charCount = 0
indcount = 0
if charStr in x['secWord']:
while occ > charCount :
pos = x['secWord'].index(charStr, indcount)
x['curGuess'][pos] = charStr
indcount = indcount + 1
charCount = charCount + 1
x['livesRem'] = x['livesRem'] - 1
I think you're also misunderstanding the second parameter of index, which is the start index to search from, not the nth occurrence to look for. What's happening right now is you're replacing the first "L" twice.
string.index(s, sub[, start[, end]]) Like find() but raise ValueError when the substring is not found.
Where find says that:
Return the lowest index in s where the substring sub is found such that sub is wholly contained in s[start:end].
So, you don't need the indcount variable, which is the nth L to find, you need the position of the last found L, plus 1. Replace "indcount" with "pos + 1" so that it searches past the last found occurrence of the letter, and it should work as intended.