The most common answer is:
my_string = “hello!”
One of the two lines below will cause an error.
Each line is an attempt to replace the first
letter of myString with H. Comment out the
line you think is incorrect.
def bad():
my_string[0] = “H”
BAD
my_string = “H” + my_string[1:]
print(my_string)
In Python, strings are immutable, meaning you cannot change their content once they are created. Attempting to directly modify a character in a string by index, as done in the bad()
function definition, will result in a TypeError
. The correct way to modify a string is to create a new string with the desired changes, as shown in the second approach. Therefore, the line that will cause an error is:
my_string[0] = “H” # BAD - This will cause a TypeError because strings are immutable.
Here’s the corrected version of the code with the problematic line commented out and standard ASCII quotation marks used:
my_string = "hello!"
# def bad():
# my_string[0] = "H" # This line is incorrect and should be commented out.
my_string = "H" + my_string[1:]
print(my_string)
This demonstrates the correct approach to replacing the first letter of my_string
with “H” by creating a new string that combines “H” with the rest of my_string
starting from index 1.