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'?
Strings are known as Immutable in Python (and other languages) because once the initial string is created, none of the function/methods that act on it change it directly, they simply return new strings.
So, in your example
After the
.replace
call, you should try evaluatingstr1
in your REPL. It might surprise you to see thatstr1
still holds the value 'Rohit'. The.replace
returns a new string in which all instances of the given character are replaced with the specified character. Your REPL will print that returned string, but after that it is lost since you didn't assign it to anything.Your second example is much the same, but with a string constant instead of a variable like
str1
.You are getting such output because that line of code does nothing to the string but creates a new string with R replaced with M (you can think it returned a variable), and in python when you simply type the name of a variale it is printed on the console. That's what created the confusion, I think.
you can check mutability by checking id of variable before and after the change
Strings don't have any methods on them that allow a change to the value of the string. In other words: strings are immutable.
When you call
str.replace
a new string is built and returned.As you can see
s1
still has its original value.