2.7 可变和不可变类型

列表是可变的(Mutable)

In [1]:

a = [1,2,3,4]
a



Out[1]:

[1, 2, 3, 4]


通过索引改变:

In [2]:

a[0] = 100
a



Out[2]:

[100, 2, 3, 4]


通过方法改变:

In [3]:

a.insert(3, 200)
a



Out[3]:

[100, 2, 3, 200, 4]


In [4]:

a.sort()
a



Out[4]:

[2, 3, 4, 100, 200]


字符串是不可变的(Immutable)

In [5]:

s = "hello world"
s



Out[5]:

'hello world'


通过索引改变会报错:

In [6]:

s[0] = 'z'



---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-6-83b06971f05e> in <module>()
----> 1 s[0] = 'z'

TypeError: 'str' object does not support item assignment


字符串方法只是返回一个新字符串,并不改变原来的值:

In [7]:

print s.replace('world', 'Mars')
print s



hello Mars
hello world



如果想改变字符串的值,可以用重新赋值的方法:

In [8]:

s = "hello world"
s = s.replace('world', 'Mars')
print s



hello Mars



或者用 bytearray 代替字符串:

In [9]:

s = bytearray('abcde')
s[1:3] = '12'
s



Out[9]:

bytearray(b'a12de')


数据类型分类:

可变数据类型 不可变数据类型
list,dictionary,set,numpy array,user defined objects integer,float,long,complex,string,tuple,frozenset

字符串不可变的原因

其一,列表可以通过以下的方法改变,而字符串不支持这样的变化。

In [10]:

a = [1, 2, 3, 4]
b = a



此时, ab 指向同一块区域,改变b 的值,a 也会同时改变:

In [11]:

b[0] = 100
a



Out[11]:

[100, 2, 3, 4]


其二,是字符串与整数浮点数一样被认为是基本类型,而基本类型在Python中是不可变的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值