Mutable and Immutable Strings in python

2019-06-26 04:50发布

问题:

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'?

回答1:

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.

>>> s1 = 'Rohit'
>>> s2 = s1.replace('R', 'M')
>>> 
>>> s1
'Rohit'
>>> s2
'Mohit'

As you can see s1 still has its original value.



回答2:

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

str1='Rohit'
str1.replace('R','M')

After the .replace call, you should try evaluating str1 in your REPL. It might surprise you to see that str1 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.



回答3:

you can check mutability by checking id of variable before and after the change

In [3]: s1 = 'Rohit'

In [4]: id(s1)
Out[4]: 140510191375440

In [5]: s1.replace('R', 'M')
Out[5]: 'Mohit'

In [6]: id(s1)
Out[6]: 140510191375440


回答4:

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.