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:
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

print(replace_at_index("eggplant", 3))

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

Following are the python program code to replace a Letter with the index value:

Python program to replace a letter:

def replace_at_index(s,i):#defining a method replace_at_index that tales two variable inside the parameter

  n=''#defining a string variable n

  for x in range(len(s)):#defining a loop that calculates the length of string value

      if x == i:#uding if that adds dash into the index of string value

          n += '-'#adding dash

      else:#else block

          n+= s[x]#defining n variable that holds string value

  return n#return string value

print(replace_at_index("eggplant", 3))#using print method that calls and prints the method value

output:

please find the attached file.

Program Explanation:

  • Defining a method "replace_at_index" that tales two-variable "s, i" inside the parameter, in which one is a string and one is an integer.
  • Inside the method, a string variable "n" is declared, and a for a loop.
  • Inside the loop, it calculates the length of the string value and use a conditional block that adds a dash into the index of the string, and uses a return that prints the calculated value.
  • Outside the method, a print method is used that calls and prints the method value.

Find out more about the string replacement here:

brainly.com/question/16952226

Ver imagen codiepienagoya
ACCESS MORE
ACCESS MORE
ACCESS MORE
ACCESS MORE