本文最后更新于 603 天前,其中的信息可能已经过时,如有错误请发送邮件到wuxianglongblog@163.com
可变与不可变类型
列表是可变的
列表是一种可变类型:
a = [1,2,3,4]可以通过索引改变:
a[0] = 100a[100, 2, 3, 4]通过方法改变:
a.insert(3, 200)a[100, 2, 3, 200, 4]a.sort()a[2, 3, 4, 100, 200]字符串是不可变的
s = "hello world"通过索引改变会报错:
s[0] = 'z'---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Input In [9], in | ()
----> 1 s[0] = 'z'
TypeError: 'str' object does not support item assignment | 字符串方法只是返回一个新字符串,并不改变原来的值:
s.replace('world', 'Mars')'hello Mars's'hello world'想改变某个字符串变量的值,只能重新赋值:
s = s.replace('world', 'Mars')s'hello Mars'