Python strings are immutable. What you're doing is just reassigning the a
variable with two different strings, that has nothing to do with immutability.
In the code shown no new variables are being created, there's just a
. And in the assignments, a
is pointed to a different string each time. To see that strings are immutable, take a look at this example:
a = 'abxde'
b = a.replace('x', 'c')
a
=> 'abxde'
b
=> 'abcde'
As you can see, a
was not modified by the replace()
method, instead that method created a new string, which we assigned to b
, and that's where the replaced string ended. All string methods that perform changes are just like that: they don't modify the original string in-place, they create and return a new one.