Strings · Class 11 · CBSE · Science Computer Science

Explain string immutability in Python and show how to change the first character of the string "cat" to produce "bat".

Practice question from Strings (Class 11 · CBSE · Science Computer Science), with the correct answer and a step-by-step solution.

hard · Subjective · Q-E3C877

Explain string immutability in Python and show how to change the first character of the string "cat" to produce "bat".

Answer: Python strings are immutable, so an individual character cannot be changed using assignment; for example, s[0] = "b" raises a TypeError. A new string must be created, such as s = "b" + s[1:] after setting s = "cat". The resulting value of s is "bat".

Solution

A string cannot be modified in place because strings are immutable. Concatenating the new first character with the slice s[1:] creates a new string.

More from Strings

All of Strings

Practise more Computer Science

Sign up free for adaptive practice on this chapter, with instant feedback and hints on every question.

Start practising free

Free to start · No credit card needed