Python之字节类型

Python之字节类型

  • 字节序列
    • python3 引入两个新的类型bytes、bytearray
    • bytes不可变字节序列,bytearray是可变字节数组。

Bytes初始化

  • bytes() 空bytes
  • bytes(int) 指定字节的bytes,被0填充
  • bytes(iterable_of_ints) -> bytes [0,255]的int组成的可迭代对象
  • bytes(string, encoding[, errors]) -> bytes 等价于string.encode()
  • bytes(bytes_or_buffer) -> immutable copy of bytes_or_buffer 从一个字节序列或者buffer复制出 一个新的不可变的bytes对象
  • 使用b前缀定义
    • 只允许基本ASCII使用字符形式b’abc9’
    • 使用16进制转义表示b"\x41\x61"

bytes类型和str类型类似,都是不可变类型,操作方法类似。

bytearray初始化

  • bytearray() 空bytearray
  • bytearray(int) 指定字节的bytearray,被0填充
  • bytearray(iterable_of_ints) -> bytearray [0,255]的int组成的可迭代对象
  • bytearray(string, encoding[, errors]) -> bytearray 近似string.encode(),不过返回可变对象 bytearray(bytes_or_buffer) 从一个字节序列或者buffer复制出一个新的可变的bytearray对象

b前缀表示的是bytes,不是bytearray类型
由于bytearray类型是可变数组,所以,类似列表。

bytes(), b'', b'abc\t\n', b'\x09'
# 字面常量一但创建不可修改,不可变类型
# 返回结果:(b'', b'', b'abc\t\n', b'\t')
b'abc' + b'123'
# 没有修改原来的,生成了一个全新的
# 返回结果:b'abc123'
b'12' * 3
# 重复3次
# 返回结果:b'121212'
b'\t\n abc\t\t\n'.strip()
# strip去除空白字符
# 返回结果:b'abc'
bytes(b'abc')
# bytes包一个bytes
# 返回结果:b'abc'
'啊'.encode(), bytes('啊', 'utf8')
# 编码
# 返回结果:(b'\xe5\x95\x8a', b'\xe5\x95\x8a')
# bytes(n) # 括号中可以写任意个
# bytes(iterable of int) # 括号可迭代对象或整形
bytes([1, 9, 10, 13, 0x41])
# 列表中的值是对应ascii编码表中的值
# 返回结果:b'\x01\t\n\rA'
bytes(range(0x61, 0x64))
# 注意range 前包后不包,所以只能看到abc
# 返回结果:b'abc'
b1 = bytes(range(0x61, 0x64))
b1[0]
# 97 对应ascii表中的a
# 返回结果:97
b1
# 返回结果:b'abc'
b2 = bytearray(range(0x41, 67))
b2
# 返回结果:bytearray(b'AB')
b2.append(67)
b2
# 返回结果:bytearray(b'ABC')
b2[0]
# 返回结果:65
b2.insert(0, 0x61)
b2
# 返回结果:bytearray(b'aABC')
b2.extend(b'abc')
b2
# 返回结果:bytearray(b'aABCabc')
b2.extend(range(0x31, 0x34))
b2
# 返回结果:bytearray(b'aABCabc123')
b2.remove(0x31)
# 删除
b2.pop()
# 弹出最后一个
b2
# 返回结果:bytearray(b'aABCabc2')
br'\x09', len(br'\x09')
# r前缀 让字符变成原本的样子
# 返回结果:(b'\\x09', 4)

你可能感兴趣的:(Python,python,开发语言)