Search code examples
pythonstringsubstring

replacing a substring in a string: Python


I am trying to continuously replace the substrings within a string based on user input but my string.replace syntax seems to replace the whole string with the substring from user input. here is the code:

import re
secret_word  = 'COMPUTER'    
clue = len(secret_word) * '-'   # this step gives the user the nos of characters in secret_word
user_guess = input("Type a single letter here, then press enter: ")
user_guess = user_guess.upper()
if user_guess in secret_word:
    index = [match.start() for match in re.finditer(user_guess, secret_word)] # this finds the index of the user guess in secret_word                                                     
    print(index)
    for i in index:
        clue  = clue.replace(clue[i], user_guess)
        print("The word now looks like this: "+ clue)

I am not sure why it is not replacing only the substrings.


Solution

  • The cause is the line clue = clue.replace(clue[i], user_guess). clue[i] will always be equal to '*' at the beginning so the replace function will replace all the characters by the user_guess.

    One solution is to change clue to be a list instead of a string clue = len(secret_word) * ['-'] and replace the replace operation by clue[i] = user_guess

    Do not forget to update the print operation: clue becomes "".join(clue) in print("The word now looks like this: "+ clue)