什么是 bytes?
在 Python 中,bytes 是一种不可变的序列类型,用于表示原始的二进制数据。
它常用于处理文件(如图片、音频)、网络通信、加密等需要直接操作字节的场景。
创建 bytes 对象
# 方法1:使用 b 前缀
b1 = b'hello'
# 方法2:使用 bytes() 构造函数
b2 = bytes([104, 101, 108, 108, 111]) # [104,101,...] 是 ASCII 码
# 方法3:从字符串编码而来
b3 = 'hello'.encode('utf-8')
常用操作示例
b = b'Python'
# 索引与切片
print(b[0]) # 输出: 80 (ASCII of 'P')
print(b[1:4]) # 输出: b'yth'
# 长度
len(b) # 6
# 拼接
b + b'!' # b'Python!'
# 成员检测
b'y' in b # True
编码与解码
str(字符串)与 bytes 之间的转换通过 encode() 和 decode() 实现:
s = "你好"
b = s.encode('utf-8') # 转为 bytes
print(b) # b'\xe4\xbd\xa0\xe5\xa5\xbd'
s2 = b.decode('utf-8') # 转回 str
print(s2) # "你好"
交互式演示
点击按钮查看 bytes 示例输出: