掌握编码与解码的核心技巧,轻松处理字节与字符串的转换
在 Python 3 中,str 表示 Unicode 字符串,而 bytes 表示原始字节序列。两者不能直接互换,必须通过编码(encode)和解码(decode)操作进行转换。
将 bytes 转换为 str 使用 .decode() 方法:
b = b'Hello, world!'
s = b.decode('utf-8')
print(s) # 输出: Hello, world!
示例:使用不同编码解码 bytes
# UTF-8
b1 = '你好'.encode('utf-8') # bytes
s1 = b1.decode('utf-8') # str
# GBK
b2 = '你好'.encode('gbk')
s2 = b2.decode('gbk')
当 bytes 中包含无法用指定编码解析的字节时,会抛出 UnicodeDecodeError。可使用 errors 参数处理:
# 忽略错误
s = b.decode('utf-8', errors='ignore')
# 替换无法解码的字符
s = b.decode('utf-8', errors='replace')
输入一段 bytes(以十六进制或字面量形式),选择编码方式,查看解码结果: