📜  为什么Python字符串是不可变的?

📅  最后修改于: 2022-05-13 01:55:48.664000             🧑  作者: Mango

为什么Python字符串是不可变的?

一成不变的文章暗指一件物品一旦制作完成,其价值就无法改变其一生。尝试执行随附的代码:

Python3
name_1 = "Aarun" 
  
name_1[0] = 'T'


Python3
name_1 = "Aarun"
  
name_2 = "T" + name_1[1:]
  
print("name_1 = ", name_1, "and name_2 = ", name_2)


Python3
name_1 = "Aarun"
name_2 = "T" + name_1[1:]
  
print("id of name_1 = ", id(name_1))
print("id of name_2 = ", id(name_2))


Python3
name_1 = "Aarun"
name_2 = "Aarun"
  
print("id of name_1 = ", id(name_1))
print("id of name_2 = ", id(name_2))


Python3
name_1 = "Aarun"
print("id of name_1 = ", id(name_1))
  
name_1 = "Tarun"
print("id of name_1  with new value = ", id(name_1))


当您需要更改字符串的内容时,您将收到一条错误消息。

Traceback (latest call last):  
Record "/home/ca508dc8fa5ad71190ca982b0e3493a8.py", line 2, in   
name_1[0] = 'T'  
TypeError: 'str' object doesn't uphold thing task  

安排

一种可能的安排是制作另一个具有重要变化的字符串对象:

蟒蛇3

name_1 = "Aarun"
  
name_2 = "T" + name_1[1:]
  
print("name_1 = ", name_1, "and name_2 = ", name_2)

输出:

name_1 =  Aarun and name_2 =  Tarun

要查看它们是各种字符串,请检查 id() 工作:

蟒蛇3

name_1 = "Aarun"
name_2 = "T" + name_1[1:]
  
print("id of name_1 = ", id(name_1))
print("id of name_2 = ", id(name_2))

输出:

id of name_1 =  2342565667256
id of name_2 =  2342565669888

要了解有关字符串持久性思想的更多信息,请考虑随附的代码:

蟒蛇3

name_1 = "Aarun"
name_2 = "Aarun"
  
print("id of name_1 = ", id(name_1))
print("id of name_2 = ", id(name_2))

在执行上述代码行时,您会发现 name_1 和 name_2 对象的 id 都暗指字符串“Aarun”,它们是等效的。

要进一步挖掘,请执行随附的断言:

蟒蛇3

name_1 = "Aarun"
print("id of name_1 = ", id(name_1))
  
name_1 = "Tarun"
print("id of name_1  with new value = ", id(name_1))

输出:

id of name_1 =  2342565667256
id of name_1  with new value =  2342565668656

在上面的模型中可以发现,当一个字符串引用被另一个值重新初始化时,它正在制作另一篇文章而不是覆盖过去的值。

注意:在Python中,字符串是不变的,因此软件工程师无法调整项目的实质。这样可以避免多余的错误。