a = [1,2,3,4]
可以通过索引改变:
a[0] = 100
a
[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 <cell line: 1>() ----> 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'