Need clarification on immutability of strings

Can someone please clarify why the study material says that strings are immutable, however, the language allows us to add characters to the end of a string as such:

def add_exclamation(word): #add "!" to the end of a word until the length of the word string is 20 for i in range(20-len(word)): word += "!" return word print(add_exclamation("Codecademy"))

Hello!

In your code, you don’t change an existing string - you create a new instance on each iteration and just use the same variable to store it. You cannot change the contents of a word without creating a new string and assigning it to a variable. But, for example, list is mutable because you can change its elements without assignment - fruits.append("orange").

So str is immutable, while list can be changed in Python.

2 Likes

I think I understood.

By word += β€œ!” I’m re-creating the string, word = word + β€œ!”. I am not changing the string in the variable word, but creating a new variable with the same name (word) that amounts to the old variable word + β€œ!”.

Am I understanding this correctly?

The variable is not new. It is simply assigned a new string value. Otherwise your understanding is correct. We’re not changing the string, but replacing it.

1 Like