Python之字节串

字节串

  • 存储以字节为单位的数据
  • 字节串是不可变的字节序列
  • 字节是 0~255 之间的整数

创建字节串

# 创建空字节串的字面值
b'' 
b""
b''''''
b""""""
B''
B""
B''''''
B""""""
# 创建非空字节串的字面值
b'ABCD'
b'\x41\x42'
b'hello Jason'

字节串的构造函数

  • bytes() 生成一个空的字节串 等同于 b''
  • bytes(整型可迭代对象) 用可迭代对象初始化一个字节串,不能超过255
  • bytes(整数n) 生成 n 个值为零的字节串
  • bytes(字符串, encoding='utf-8') 用字符串的转换编码生成一个字节串
a = bytes()  # b''
b = bytes([10,20,30,65,66,67])  # b'\n\x14\x1eABC'
c = bytes(range(65,65+26))  # b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
d = bytes(5)  # b'\x00\x00\x00\x00\x00'
e = bytes('hello 中国','utf-8')  # b'hello \xe4\xb8\xad\xe5\x9b\xbd'

字节串的运算

  • + += * *=
  • < <= > >= == !=
  • in / not in 只能对整型数进行操作
  • 索引/切片
b = b'abc' + b'123'  # b=b'abc123'
b += b'ABC'    # b=b'abc123ABC'
b'ABD' > b'ABC'  # True
b = b'ABCD'
65 in b    # True
b'A' in b  # True

bytesstr 的区别

  • bytes 存储字节(0-255)
  • str 存储Unicode字符(0-65535)

bytesstr 转换

  • strbytes
    b = s.encode('utf-8')
  • bytesstr
    s = b.decode('utf-8')

字节数组

  • 可变的字节序列

创建字构造函数

  • bytearray() 生成一个空的字节串 等同于 bytearray(b'')
  • bytearray(整型可迭代对象) 用可迭代对象初始化一个字节串,不能超过255
  • bytearray(整数n) 生成 n 个值为零的字节串
  • bytearray(字符串, encoding='utf-8') 用字符串的转换编码生成一个字节串
a = bytearray() # bytearray(b'')
b = bytearray(5) # bytearray(b'\x00\x00\x00\x00\x00')
c = bytearray([1,2,3,4]) # bytearray(b'\x01\x02\x03\x04')

字节数组的运算

  • + += * *=
  • < <= > >= == !=
  • in / not in 只能对整型数进行操作
  • 索引/切片

字节数组的方法

  • B.clear() 清空字节数组
  • B.append(n) 追加一个字节(n为0-255的整数)
  • B.remove(value) 删除第一个出现的字节,如果没有出现,则产生ValueError错误
  • B.reverse() 字节的顺序进行反转
  • B.decode(encoding='utf-8') # 解码
  • B.find(sub[, start[, end]]) 查找

你可能感兴趣的:(Python之字节串)