Try it on paper first. A hint, the key idea and the worked solution are here when you need them.
A student wants to change the name "Rahul" to "Raju" and writes
Python stops with a TypeError. Explain why, and write a correct program that shows Raju.
Have you tried it?
Work it out on paper first. It is fine to get stuck or make a mistake: that is how we learn. When you are ready, go through the solution one step at a time, and check each step against your own.
Plan. Read the message: 'str' object does not support item assignment. A string cannot be changed in place.
Step 1. name[3] = "j" tries to put a new letter in position 3. Strings do not allow it. This is the line that stops the program.
Step 2. We must make a new string and store it in name. The new string is the first two letters, Ra, then ju. That is Raju.
Step 3. name[:2] is Ra, and "Ra" + "ju" is Raju.
Check. The new name has four letters, R, a, j and u.
Answer: A string is immutable. Use a slice and + to build the new string, and store it in the same name.
Log in to join the discussion.
Loading…