I was just going through mutable and immutable structures in python. It was written that "Strings are immutable" in Python i.e We cannot alter them Consider the code:
str1='Rohit'
str1.replace('R','M')
This gives the output:
'Mohit'
Now, somebody said that it is the variable str1 which is pointing to the string 'Rohit' and after str1.replace() it points to 'Mohit' Consider this code:
'Rohit'.replace('R','M')
This also gives me the output:
'Mohit'
Then what is meant by 'Strings are immutable'?
str1
will not change unless you dostr1 = str1.replace(...)
, in which case it is assigned a new string, and the old one is discarded, but not changed. – Tini+=
(ie. append) works is even more perplexing WRT "immutability". – Tarn