Skip to main content

Section 15.3 Strings are Immutable

Even though you can manipulate a string to create a new string the original string is immutable which means that they never change. Notice that after you execute the code below the string stored in the variable sentence hasn’t changed.
While the strings themselves can’t be changed you can change the value of a variable. This throws away the original string and sets the variable’s value to the new string.
We can reassign a variable to hold the result of calling a function on a string. On line 3 of the example below, we make the new value of sentence be the result of changing the old value of sentence after it was changed to lowercase.

Note 15.3.1.

We always do all the work on the right side of = and then store the result in the variable listed on the left side.

Checkpoint 15.3.2.

    Given the following code segment, what is the value of the string s1 after these are executed?
    s1 = "xy"
    s2 = s1
    s1 = s1 + s2 + "z"
    
  • xyz
  • s1 will equal "xy" plus another "xy" and then "z" at the end.
  • xyxyz
  • s1 contains the original value, plus itself, plus "z"
  • xy xy z
  • No spaces are added during concatenation.
  • xy z
  • No spaces are added during concatenation, and an additional "xy" should be included at the beginning.
  • z
  • s1 was set to "xy" initially, so the final answer will be "xyxyz"

Checkpoint 15.3.3.

    What is the value of s1 after the following code executes?
    s1 = "HEY"
    s2 = s1.lower()
    s3 = s2.capitalize()
    
  • Hey
  • This would be correct if we had asked what the value of s3 was. What is the value of s1?
  • hey
  • This would be true if we asked what the value of s2 was after the code executes. What is the value of s1?
  • HEY
  • Strings are immutable, meaning they don’t change. Any function that changes a string returns a new string. So s1 never changes unless you set it to a different string.
You have attempted of activities on this page.