Replace a certain index of a string in python 3.0 -
i need replace character in string here catch, string underscores , need able replace underscore corresponds index of word. example:
underscore = '___' word = 'cow' guess = input('input letter guess') #user inputs letter o illustration if guess in word: underscore = underscore.replace('_',guess)
what need fixed underscore gets replaced needs in sec place of 3 underscores. dont want underscore = 'o__'
rather '_o_'
you have exclude other characters word
, , form new string this
def replacer(word, guess): homecoming "".join('_' if char != guess else char char in word) assert(replacer("cow", "o") == "_o_")
this work if there multiple occurrences of guessed character
assert(replacer("bannana", "n") == "__nn_n_")
the replacer
function, iterates word
, character character , on each iteration, current character in char
variable. then, decide should filled in place of current character, in resulting string with
'_' if char != guess else char
this means that, if current character not equal guessed character, utilize _
otherwise utilize character is. , characters joined "".join
.
python string
No comments:
Post a Comment