Python 中 bytes 与 str 如何互转?
bytes 转 str 用 decode('utf-8'),str 转 bytes 用 encode('utf-8')。本文给出互转示例、常见编码错误(UnicodeDecodeError)处理与 b 前缀说明。
两个方法:b'你好'.decode('utf-8') 把字节解码成字符串;'你好'.encode('utf-8') 把字符串编码成字节。编码必须一致——用什么编码 encode 就用什么 decode。
互转示例
# str → bytes
s = 'hello 你好'
b = s.encode('utf-8') # b'hello \xe4\xbd\xa0\xe5\xa5\xbd'
# bytes → str
s2 = b.decode('utf-8') # 'hello 你好'
常见错误处理
# 字节里混有非法编码时的兜底
b.decode('utf-8', errors='replace') # 非法字节替换为
b.decode('utf-8', errors='ignore') # 直接丢弃
网络数据、文件二进制内容常见 UnicodeDecodeError: 'utf-8' codec can't decode——要么换正确编码(如 gbk),要么用 errors 参数兜底。
注意
- Python 3 中 str 是 Unicode,bytes 是字节序列,两者不能直接拼接:
'a' + b'b'报 TypeError; - 带
b前缀的字面量是 bytes:b'abc'。
常见问题(FAQ)
Q:怎么判断一个变量是 str 还是 bytes? isinstance(x, bytes) / type(x)。
Q:base64 之后是什么类型? base64.b64encode() 返回 bytes,要显示需再 decode('ascii')。