131,194 views
17 votes
17 votes
7.2.8: Part 2, Replace a Letter

"Write a function called replace_at_index that takes three arguments - a string, an integer (representing an index), and a string. Return a string that is the same as the first string, except with the character at the specified index replaced by the second string.

Ask the user for some text, which index to replace, and what to replace that index with (in that order!).

Print out the result of calling your function.

If the user enters the following input:

Enter a word or phrase: dog
Enter an index value: 0
Enter the new letter: f
The following should be output:

fog"

User Belurd
by
3.3k points

1 Answer

4 votes
4 votes

def replace_at_index(txt, ind, let):

new_txt = ""

for x in range(len(txt)):

if x == ind:

new_txt += let

else:

new_txt += txt[x]

return new_txt

print(replace_at_index(input("Enter a word or phrase: "), int(input("Enter an index value: ")), input("Enter the new letter: ")))

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

User Letsc
by
3.3k points