7.2.7: Part 1, Replace a Letter

"Write a function named replace_at_index that takes a string and an integer. The function should return a new string that is the same as the old string, EXCEPT with a dash in place of whatever character was at the index indicated by the integer.

Call your function on the word eggplant and the index 3, like this:

s = replace_at_index("eggplant", 3)
You should then print the value of s, which should display:

egg-lant"

Respuesta :

def replace_at_index(txt,ind):

   new_txt = ""

   for x in range(len(txt)):

       if x == ind:

           new_txt += "-"

       else:

           new_txt += txt[x]

   return new_txt

s = replace_at_index("eggplant", 3)

print(s)

I wrote my code in python 3.8. I hope this helps.

Answer:

def replace_at_index(string, index):

   return string[0:index]+"-"+string[index+1:]

   

replaced_word = replace_at_index("house", 0)

print(replaced_word)

Explanation:

simpler version