Are strings always immutable?

I thought that strings were immutable, but in the exercise “reverse” from the module Practice Makes Perfect, you create a string variable within a function and add a letter to it for every loop in the while statement. Is this possibly because the string is not being changed, but the variable is being reassigned, and getting a new set of information, that happens to include the old one?
The code from the solution:

def reverse(text):
word = “”
l = len(text) - 1
while l >= 0:
word = word + text[l]
l -= 1
return word

Strings in Python do not support item replacement or insertion, so yes, immutable.

string = 'gale'
string[3] = 'a'             # cannot be done

We can replace a string with another string…

string = string[:3] + 'a'
print (string)              # gala

Notice we are assigning a new value to the variable. We haven’t changed the string, directly, but replaced it with another value (in truth, we have pointed it to another value).

string += 'xy'
print (string)              # galaxy

Again, we are not modifying the string. The change takes place when we concatenate ‘gala’ with ‘xy’ and assign it back onto the same variable.

If you are coming from JavaScript or Java this is not new. Neither of those languages support item replacement or insertion. C++ on the other hand does support item replacement, as I understand it.

string[3] = 'a'

will mutate the string from ‘gale’ to ‘gala’.

1 Like

Immutable strings is a feature, not a restriction
The kind of change you’re talking about is something that list supports, therefore that is what you would use for this kind of operation
And yes, string’s + creates an entirely new string, everything gets copied into the new string

In this particular case some python implementations do an optimization where it’s possible to tell that nobody is using the old string, and therefore changes the original regardless. However that isn’t something to rely on, you should write what you mean. (And you definitely shouldn’t expect python to do anything clever like this anywhere else, it generally does exactly what you say, the way you say it)