I need to replace a character in a string but here is the catch, the string will be all underscores and I need to be able to replace the underscore that corresponds to the index of the word. For example:
underscore = '___'
word = 'cow'
guess = input('Input the your letter guess') #user inputs the letter o for example
if guess in word:
underscore = underscore.replace('_',guess)
what i need to be fixed is that the underscore that gets replaced needs to be in the second place of the three underscores. I dont want underscore = 'o__' but rather '_o_'
3 Answers 3
You just have to exclude all other characters from word, and form a new string like this
def replacer(word, guess):
return "".join('_' if char != guess else char for char in word)
assert(replacer("cow", "o") == "_o_")
This will work even if there are multiple occurrences of the guessed character
assert(replacer("bannana", "n") == "__nn_n_")
The replacer function, iterates the word, character by character and on each iteration, the current character will be in char variable. Then, we decide what should be filled in place of the current character, in the resulting string with
'_' if char != guess else char
This means that, if the current character is not equal to the guessed character, then use _ otherwise use the character as it is. And finally all those characters are joined together with "".join.
1 Comment
Strings in Python are immutable. You can't change them. You can only redefine them.
An easy way to do this is to find the index of the relevant letter:
index = "cow".index("o")
and then to just take the rest that you need from your word using slice notation:
newword = word[:index] + yourletterhere + word[index+1:]
for example:
>>> "bananaphone".index("p")
6
>>> "bananaphone"[:6]
'banana'
>>> "bananaphone"[7:]
'hone'
>>> "bananaphone"[:6] + "x" + "bananaphone"[7:]
'bananaxhone'
#Find the index position of second occurrence of '_'
i = underscore.find("_",underscore.find('_')+1)
#Create a new string with the requirements
newstr = underscore[:i] + 'o' + underscore[i+1:]
print(newstr)
>>> underscore = "___"
>>> i = underscore.find("_",underscore.find('_')+1)
>>> newstr = underscore[:i] + 'o' +underscore[i+1:]
>>> print(newstr)
_o_