python :字节串
1、字节串bytes (也叫字节序列)
【1】存储以字节为单位的数据
【2】字节串是不可变的序列
2、字节
【1】一个字节是由8个位(bit)组成的数据单位,是计算机进行数据管理的单位
【2】字节是用 0 ~ 255 范围内的整数表示的
3、字节串的形式
【1】B = b“” 或 B = B“” #空字节串
【2】q = b"asd"
【3】bytes() 生成一个空的字节串 等同于 b''
【4】bytes(整数可迭代对象) # 用可迭代对象初始化一个字节串
In [83]: bytes([1,2,3])
Out[83]: b'\x01\x02\x03'
In [84]: bytes((1,2,3))
Out[84]: b'\x01\x02\x03'
In [85]: bytes({1,2,3})
Out[85]: b'\x01\x02\x03'
In [86]: bytes({1:"sd",2:"dsa",3:"eq"})
Out[86]: b'\x01\x02\x03'
In [88]: bytes("123")
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-88-87bf03f6e600> in <module>
----> 1 bytes("123")
TypeError: string argument without an encoding
【5】bytes(整数n) 生成n个值为0的字节串 # bytes(5) ---》b'\x00\x00\x00\x00\x00'
【6】bytes(字符串, encoding='utf-8') 用字符串转为编码生成一个字节串
In [82]: bytes("asda",encoding="utf-8")
Out[82]: b'asda'
4、字节串的运算
+ += * *=
< <= > >= == !=
in / not in
索引和切片
5、bytes 和 str 的区别
【1】bytes 存储字节( 通常值在 range(0, 256))
【2】str 存储unicode字符( 通常值在0~65535)
6、bytes 与 str 的转换
编码(encode)
str ------------> bytes
b = s.encode(encoding='utf-8')
解码(decode)
bytes ----------> str
s = b.decode(encoding='utf-8')