在Python中,encode() 和 decode() 方法是用于字符串(str)和字节(bytes)之间转换的核心方法,主要涉及字符编码的处理。
一、基本概念
编码(Encode)
将 字符串(str) 转换为 字节(bytes)
-
字符串 → 字节
-
人类可读文本 → 计算机存储/传输格式
解码(Decode)
将 字节(bytes) 转换为 字符串(str)
-
字节 → 字符串
-
计算机存储/传输格式 → 人类可读文本
二、基本用法
1. encode() 方法
python
# 基本语法
str.encode(encoding='utf-8', errors='strict')
# 示例
text = "你好,世界!"
byte_data = text.encode('utf-8')
print(byte_data) # b'\xe4\xbd\xa0\xe5\xa5\xbd\xef\xbc\x8c\xe4\xb8\x96\xe7\x95\x8c\xef\xbc\x81'
print(type(byte_data)) # <class 'bytes'>
2. decode() 方法
python
# 基本语法
bytes.decode(encoding='utf-8', errors='strict')
# 示例
byte_data = b'\xe4\xbd\xa0\xe5\xa5\xbd'
text = byte_data.decode('utf-8')
print(text) # 你好
print(type(text)) # <class 'str'>
3. error参数详解
python
text = " café " # 包含特殊字符
# 1. strict(默认) - 遇到错误抛出异常
try:
text.encode('ascii') # 会失败
except UnicodeEncodeError as e:
print(f"错误: {e}")
# 2. ignore - 忽略无法编码的字符
result = text.encode('ascii', errors='ignore')
print(result) # b' caf '
# 3. replace - 用?替换无法编码的字符
result = text.encode('ascii', errors='replace')
print(result) # b' caf? '
# 4. xmlcharrefreplace - 用XML实体替换
result = text.encode('ascii', errors='xmlcharrefreplace')
print(result) # b' café '
# 5. backslashreplace - 用Unicode转义序列替换
result = text.encode('ascii', errors='backslashreplace')
print(result) # b' caf\\xe9 '
# 6. namereplace - 用\N{...}替换
result = text.encode('ascii', errors='namereplace')
print(result) # b' caf\\N{LATIN SMALL LETTER E WITH ACUTE} '
4. 文件读写
python
# 写入文件(编码)
with open('test.txt', 'w', encoding='utf-8') as f:
f.write("中文内容")
# 读取文件(解码)
with open('test.txt', 'r', encoding='utf-8') as f:
content = f.read()
# 二进制模式需要手动编解码
with open('test.txt', 'wb') as f:
f.write("中文内容".encode('utf-8'))
with open('test.txt', 'rb') as f:
content = f.read().decode('utf-8')
5. 网络通信
python
import socket
# 发送数据
data_to_send = "请求数据".encode('utf-8')
socket.send(data_to_send)
# 接收数据
received_bytes = socket.recv(1024)
received_text = received_bytes.decode('utf-8')
6.编解码应该一致
python
# 错误示例
text = "中文"
gbk_bytes = text.encode('gbk')
try:
wrong_text = gbk_bytes.decode('utf-8') # 解码错误!
except UnicodeDecodeError:
print("编码不一致导致解码失败")
# 正确做法:保持编码一致
correct_text = gbk_bytes.decode('gbk')
最佳实践
-
始终明确指定编码,不要依赖默认值
-
统一使用UTF-8 作为项目标准编码
-
尽早解码,晚点编码:在程序内部使用字符串,只在I/O时进行编解码
-
处理异常:始终处理可能的编解码异常
-
文档说明:在项目文档中明确说明使用的编码