不变性
这意味着不能更新字符串中的字符。例如不能从字符串中删除一个元素或尝试在其任何索引位置分配一个新元素。如果尝试更新字符串,它会抛出 TypeError:
immutable_string = "Accountability"
# Assign a new element at index 0
immutable_string[0] = 'B'
Output:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_11336/2351953155.py in
2
3 # Assign a new element at index 0
----> 4 immutable_string[0] = 'B'
TypeError: ‘str’ object does not support item assignment
但是可以将字符串重新分配给 immutable_string 变量,不过应该注意它们不是同一个字符串,因为它们不指向内存中的同一个对象。Python 不会更新旧的字符串对象;它创建了一个新的,正如通过 ids 看到的那样:
immutable_string = "Accountability"
print(id(immutable_string))
immutable_string = "Bccountability"
print(id(immutable_string)
test_immutable = immutable_string
print(id(test_immutable))
Output:
2693751670576
2693751671024
2693751671024
上述两个 id 在同一台计算机上也不相同,这意味着两个 immutable_string 变量都指向内存中的不同地址。将最后一个 immutable_string 变量分配给 test_immutable 变量。可以看到 test_immutable 变量和最后一个 immutable_string 变量指向同一个地址
连接
将两个或多个字符串连接在一起以获得带有 + 符号的新字符串。例如:
first_string = "Zhou"
second_string = "luobo"
third_string = "Learn Python"
fourth_string = first_string + second_string
print(fourth_string)
fifth_string = fourth_string + " " + third_string
print(fifth_string)
Output:
Zhouluobo
Zhouluobo Learn Python