掌握字节操作,提升数据处理能力
在 Python 中,bytes 是一种不可变的序列类型,用于表示原始的二进制数据(即字节)。
每个元素是一个介于 0 到 255 之间的整数。
它常用于处理文件、网络通信、加密等涉及底层数据的场景。
b 前缀开头,如 b'hello'bytes() 构造函数'hello'.encode('utf-8')# 示例:创建 bytes
b1 = b'hello'
b2 = bytes([104, 101, 108, 108, 111]) # [104='h', ...]
b3 = 'hello'.encode('utf-8')
print(b1 == b2 == b3) # True
str 表示文本(Unicode 字符),而 bytes 表示原始字节。
两者不能直接拼接或比较,必须通过 .encode() 和 .decode() 转换。
text = "你好"
b = text.encode('utf-8') # str → bytes
text2 = b.decode('utf-8') # bytes → str
len(b):获取字节长度b[0]:访问单个字节(返回 int)b.upper(), b.lower():仅适用于 ASCII 字母b.replace(old, new):替换子字节序列b.startswith(prefix) / endswith(suffix)点击下方按钮,在控制台查看运行结果(模拟演示):