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.

 
1
greeting: str
2
greeting = "Hello, world!"
3
greeting[0] = 'J'            # ERROR!
4
print(greeting)
5

(cg08_imm1)

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)




You have attempted 1 of 3 activities on this page
Next Section - 9.8. The Accumulator Pattern with Strings