Python是不可变的字符串

Mar*_*ace 2 python

如果python字符串是不可变的,如何更改如下:

  a = "abc"
  print a
  a = "cde"
  print a
Run Code Online (Sandbox Code Playgroud)

输出:

abc
cde
Run Code Online (Sandbox Code Playgroud)

这实际上是在创建一个新变量并改为指向它吗?

Ósc*_*pez 5

Python字符串不可变的.你正在做的只是a用两个不同的字符串重新分配变量,这与不变性无关.

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'
Run Code Online (Sandbox Code Playgroud)

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.