9.3. Immutable Strings

In Python, as in many programming languages, strings are immutable. What does that mean? When something is mutable it can change. When something is immutable, it cannot change. So, when we create a string, some memory is allocated to store that string. When we want to change that string, we have to actually create a new string. This is one of the ways that strings and lists differ. Examine the code below.

In the above example, you see that it is possible to edit a list and replace one of the items with another item. But it isn’t possible to edit a string that has already been created, and change one of the letters. If you want to do that, you need to create a new string.

9.3.1. String methods return a new string

There are many built-in methods that can be used on strings. For example, if you want to make all the alphabetic characters in a string uppercase letters, you can call the .upper() method on a string. But, because strings are immutable, this method returns a new string, which has to be captured in a variable.

In the example above we create a string, and then call the upper() method on that string, storing the resulting new string in a different variable. You can see that the original string (name) is not modified by calling the upper() method on it.

Of course, often when we call string methods, we do want to change them. So, we often just reassign back to the same variable.The code above can be modified to do just that:

Forgetting that strings are immutable and not capturing the return value is a really common mistake that novice programmers make. In the code below, a novice programmer is expecting to print out a message in all lowercase letters, but the code doesn’t work because they forgot to capture the result of calling the string method lower().

Fix the above program so that the title is printed out all in lowercase. Capture the result of the string method call on line 3, and use that variable in the print statement on line 4.

You have attempted of activities on this page