byte和bytearray

Python 3 特有的,Python2是不区分bytes和str。

bytes是不可变的。

Python 2 中:

1
2
3
4
5
type(b'xxxx')
<type 'str'>
type('xxxx')
<type 'str'>

Python 3 中:

1
2
3
4
5
In [1]: type(b'xxxx')
Out[1]: bytes
In [3]: type('xxxx')
Out[3]: str

bytesstr 的区别在于,bytesbyte的序列,而strunicode的序列。

str可使用encode的方法转化为bytes

bytes使用decode的方法转化为str

(默认的encodedecode的编码方式为utf-8)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
In [4]: s = '于龙君'
In [5]: b = s.encode()
In [6]: b
Out[6]: b'xe4xbax8exe9xbex99xe5x90x9b'
In [7]: b.decode()
Out[7]: '于龙君'
In [8]: for x in s:
...: print(x)
...:
In [9]: for x in b:
...: print(x)
...:
228
186
142
233
190
153
229
144
155

bytearray

bytearray和bytes不一样的地方在于,bytearray是可变的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
In [10]: s = '于龙君'
In [11]: ba = bytearray(s.encode())
In [12]: ba
Out[12]: bytearray(b'xe4xbax8exe9xbex99xe5x90x9b')
In [13]: ba.decode()
Out[13]: '于龙君'
In [14]: ba[:3] = bytearray('王'.encode())
In [15]: ba
Out[16]: bytearray(b'xe7x8ex8bxe9xbex99xe5x90x9b')
In [17]: ba.decode()
Out[17]: '王龙君'