Skip to Content

Python Basics: Why Do You Get TypeError When Trying to Change Character in Python String?

What Does the Error “‘str’ object does not support item assignment” Mean in Python?

Understand why Python strings are immutable, meaning they cannot be changed after creation. Learn why attempting to modify a string character using item assignment raises a TypeError and discover the correct method for creating a modified string.

Question

What happens with s = “hello”; s[0] = ‘H’?

A. It becomes “hello” silently
B. It becomes “Hello”
C. It raises a TypeError
D. It raises a NameError

Answer

C. It raises a TypeError

Explanation

Attempting item assignment on a string triggers a TypeError.

The reason for this error is a fundamental property of Python strings: they are immutable. Immutability means that once a string object is created, its contents cannot be altered. The line s[0] = ‘H’ is an attempt at item assignment—trying to change a part of the string object in-place. Because the str type does not support this operation, Python raises a TypeError with the specific message: ‘str’ object does not support item assignment.

While you can access individual characters using an index (e.g., s[0] returns ‘h’), you cannot use an index to assign a new character.

To achieve the desired result of changing “hello” to “Hello”, you must create a new string and reassign the variable s to it. The standard way to do this is by combining slicing and concatenation:

s = "hello"
s = 'H' + s[1:] # This creates a new string "Hello" and assigns it to s
print(s) # Output: Hello

Here, s[1:] creates a new string ‘ello’, which is then concatenated with ‘H’ to form a completely new string object, ‘Hello’.

The other options are incorrect:

  • Python does not silently fail this operation; it raises an explicit error.
  • The code does not successfully change the string to “Hello” because the operation itself is invalid.
  • A NameError is raised when a variable is not defined. In this case, s is defined, so the error is related to the type of operation, not the name.

Python Basics: Learn, Apply & Build Programs certification exam assessment practice question and answer (Q&A) dump including multiple choice questions (MCQ) and objective type questions, with detail explanation and reference available free, helpful to pass the Python Basics: Learn, Apply & Build Programs exam and earn Python Basics: Learn, Apply & Build Programs certificate.