9.7. Strings are ImmutableΒΆ

One final thing that makes strings different from some other Python collection types is that you are not allowed to modify the individual characters in the collection. It is tempting to use the [] operator on the left side of an assignment, with the intention of changing a character in a string. For example, in the following code, we would like to change the first letter of greeting.

Instead of producing the output Jello, world!, this code produces the runtime error TypeError: 'str' object does not support item assignment.

Check your understanding

    strings-9-1: What is printed by the following statements:

    s: str
    s = "Ball"
    s[0] = "C"
    print(s)
    
  • Ball
  • Assignment is not allowed with strings.
  • Call
  • Assignment is not allowed with strings.
  • Error
  • Yes, strings are immutable.
You have attempted of activities on this page
9.6. Traversal and the for Loop: By Index"> 9.8. The Accumulator Pattern with Strings">Next Section - 9.8. The Accumulator Pattern with Strings