python - change char in string by position -


question : write function accepts 3 parameters, string , 2 integers. string represents word in guessing game. 2 integer represent positions keep letters starting point. remaining letters should replaced * symbol. function should return resulting string.

the doctests below should make clear:

def hangman_start(strng, pos1, pos2):     """     >>> hangman_start("banana", 0, 5)     'b****a'     >>> hangman_start("passionfruit", 0, 7)     'p******f****'     >>> hangman_start("cherry", 3, 4)     '***rr*'     >>> hangman_start("peach", 2, 10)     '**a**'     >>> hangman_start("banana", -1, -1)     '******'     """ if __name__=="__main__":     import doctest     doctest.testmod(verbose=true) 

i tried below:

def hangman_start(strng, pos1, pos2):         count=0     result=""     while count<len(strng):         if strng[count]==strng[pos1] or strng[count] == strng[pos2]:              result += strng[count]         else:             result += "*"         count+=1     return result 

but not work properly. such as: hangman_start("banana", 0, 5) got ba*a*a.

any kind guy can me this?

if understand correctly, want replace characters except on provided positions *:

def hangman_start(strng, pos1, pos2):   return "".join([char if index in (pos1,pos2) else '*' index, char in enumerate(strng)])  print hangman_start("asdasd", 3, 4) 

the above prints

***as* 

if want stick implementation, replace character-at-index comparison index comparison:

def hangman_start(strng, pos1, pos2):   count=0   result=""   while count<len(strng):     if count == pos1 or count == pos2:       result += strng[count]     else:       result += "*"     count+=1   return result 

while input here not large enough matter, i'd suggest append list , join list, rather append string, much, much more efficient:

def hangman_start(strng, pos1, pos2):   count=0   result=[]   while count<len(strng):     if count == pos1 or count == pos2:       result.append(strng[count])     else:       result.append("*")     count+=1   return "".join(result) 

like said, input not large enough matter in case, it's habit adopt.


Comments