Study Guide

7.2.8 Part 2, Replace a Letter CodeHS Answers

7.2.8 Part 2, Replace a Letter CodeHS Answers

The most common answer is:

string = "Pepper"
index = 3
string2 = "e"

def replace_at_index(string, index, string2):
    return string[:index] + string2 + string[index+1:]

print(replace_at_index(string, index, string2))

In this example, the character at index 3 of the string “Pepper” is replaced with “e”, resulting in “Pepeer”. This function is versatile and can replace a character at any given index with another character or even a substring (string2).