当前位置:  首页>> 技术小册>> Python合辑3-字符串用法深度总结

不变性

这意味着不能更新字符串中的字符。例如不能从字符串中删除一个元素或尝试在其任何索引位置分配一个新元素。如果尝试更新字符串,它会抛出 TypeError:

  1. immutable_string = "Accountability"
  2. # Assign a new element at index 0
  3. immutable_string[0] = 'B'

Output:

  1. ---------------------------------------------------------------------------
  2. TypeError Traceback (most recent call last)
  3. ~\AppData\Local\Temp/ipykernel_11336/2351953155.py in
  4. 2
  5. 3 # Assign a new element at index 0
  6. ----> 4 immutable_string[0] = 'B'

TypeError: ‘str’ object does not support item assignment
但是可以将字符串重新分配给 immutable_string 变量,不过应该注意它们不是同一个字符串,因为它们不指向内存中的同一个对象。Python 不会更新旧的字符串对象;它创建了一个新的,正如通过 ids 看到的那样:

  1. immutable_string = "Accountability"
  2. print(id(immutable_string))
  3. immutable_string = "Bccountability"
  4. print(id(immutable_string)
  5. test_immutable = immutable_string
  6. print(id(test_immutable))

Output:

  1. 2693751670576
  2. 2693751671024
  3. 2693751671024

上述两个 id 在同一台计算机上也不相同,这意味着两个 immutable_string 变量都指向内存中的不同地址。将最后一个 immutable_string 变量分配给 test_immutable 变量。可以看到 test_immutable 变量和最后一个 immutable_string 变量指向同一个地址
连接
将两个或多个字符串连接在一起以获得带有 + 符号的新字符串。例如:

  1. first_string = "Zhou"
  2. second_string = "luobo"
  3. third_string = "Learn Python"
  4. fourth_string = first_string + second_string
  5. print(fourth_string)
  6. fifth_string = fourth_string + " " + third_string
  7. print(fifth_string)

Output:

  1. Zhouluobo
  2. Zhouluobo Learn Python