在 Python 中,将 Unicode 字符串(str 类型)转换为 GBK 编码的字节串(bytes 类型)非常简单,核心方法是使用字符串的 .encode() 方法。

核心方法
# 语法
bytes_object = unicode_string.encode('gbk')
unicode_string: 这是你的 Python 3 字符串(str类型),它内部使用 Unicode 存储。'gbk': 这是你要指定的编码名称。bytes_object: 这是返回的结果,是一个bytes类型的对象,包含了 GBK 编码后的字节。
详细示例
示例 1:基本转换
这是一个最直接的例子,将一个包含中文字符的字符串转换为 GBK 编码。
# 1. 定义一个 Unicode 字符串 (Python 3 中 str 类型默认就是 Unicode)
unicode_str = "你好,世界!Hello, World!"
# 2. 使用 encode() 方法将其转换为 GBK 编码的字节串
# GBK 是一个中文编码,能很好地处理中文字符
gbk_bytes = unicode_str.encode('gbk')
# 3. 打印结果
print(f"原始字符串 (类型: {type(unicode_str)}): {unicode_str}")
print(f"转换后的字节串 (类型: {type(gbk_bytes)}): {gbk_bytes}")
# 你会看到输出类似这样,每个汉字和字母都对应一个或两个字节
# b'\xe4\xbd\xa0\xe5\xa5\xbd\xef\xbc\x8c\xe4\xb8\x96\xe7\x95\x8c\x21Hello, World!'
示例 2:处理无法编码的字符
如果字符串中包含 GBK 编码无法表示的字符(例如某些生僻字、emoji 或其他语言的特殊符号),.encode() 方法会抛出 UnicodeEncodeError 错误。
# 包含一个 GBK 无法编码的字符:€ (欧元符号)
problematic_str = "价格:€100"
try:
# 默认情况下,遇到无法编码的字符会报错
gbk_bytes = problematic_str.encode('gbk')
except UnicodeEncodeError as e:
print(f"编码失败!错误信息: {e}")
示例 3:处理无法编码的字符(解决方案)
当遇到无法编码的字符时,你有几种处理方式,通过 errors 参数指定:
ignore: 忽略无法编码的字符。replace: 将无法编码的字符替换成一个占位符(通常是 )。xmlcharrefreplace: 将无法编码的字符替换成对应的 XML 数字实体。
problematic_str = "价格:€100"
# 1. 使用 'ignore' 忽略掉 € 符号
bytes_ignore = problematic_str.encode('gbk', errors='ignore')
print(f"使用 'ignore': {bytes_ignore}")
# 输出: b'\xB9\xE3\xB6\xAB\x31100'
# 2. 使用 'replace' 将 € 符号替换成 ?
bytes_replace = problematic_str.encode('gbk', errors='replace')
print(f"使用 'replace': {bytes_replace}")
# 输出: b'\xB9\xE3\xB6\xAB\x3F100'
# 3. 使用 'xmlcharrefreplace' 将 € 符号替换成实体 €
# (注意:这通常用于生成文本文件,而不是二进制数据)
bytes_xmlcharref = problematic_str.encode('gbk', errors='xmlcharrefreplace')
print(f"使用 'xmlcharrefreplace': {bytes_xmlcharref}")
# 输出: b'\xB9\xE3\xB6\xAB€100'
重要区别:Python 2 vs Python 3
这个问题的答案在 Python 2 和 Python 3 中有根本性的不同,了解这一点非常重要。

Python 3 (推荐)
在 Python 3 中,字符串和字节是严格区分的:
str: 字符串,序列,内部存储为 Unicode,用于文本处理。bytes: 字节串,序列,存储的是原始字节,用于网络传输、文件读写等。
转换规则:
str->bytes: 使用.encode()方法。bytes->str: 使用.decode()方法。
# Python 3
s = "你好" # 这是一个 str (Unicode)
b = s.encode('gbk') # 转换为 bytes
print(b) # 输出: b'\xC4\xE3\xBA\xC3'
# 如果从一个文件或网络中读取了 gbk 编码的字节,需要解码
original_s = b.decode('gbk')
print(original_s) # 输出: 你好
Python 2 (已过时)
在 Python 2 中,情况比较混乱:
str: 字节串,它的编码取决于文件的声明或环境变量,如果你在代码顶部写了# -*- coding: utf-8 -*-,strUTF-8 编码的。unicode: 真正的 Unicode 字符串。
转换规则:

unicode->str: 使用.encode()方法。str->unicode: 使用.decode()方法。
# Python 2
# 假设文件编码是 UTF-8
u = u"你好" # 这是一个 unicode 对象
s = u.encode('gbk') # 转换为 gbk 编码的 str
print(s) # 输出: 你好 (在终端显示,但内部是 gbk 字节)
# 从 gbk 编码的 str 恢复到 unicode
original_u = s.decode('gbk')
print(original_u) # 输出: 你好
完整工作流程示例
假设你有一个包含中文字符的字符串,你想将它保存到一个 GBK 编码的文本文件中。
# 1. 准备你的 Unicode 字符串
content = "这是一个测试文件,用于保存为 GBK 编码。"
# 2. 将字符串编码为 GBK 格式的字节串
# 使用 errors='ignore' 或 'replace' 可以避免程序因特殊字符而崩溃
encoded_content = content.encode('gbk', errors='replace')
# 3. 以二进制写入模式 ('wb') 打开文件并写入字节串
# 注意:必须是 'wb' (write binary),而不是 'w' (write text)
with open('output_gbk.txt', 'wb') as f:
f.write(encoded_content)
print("文件已成功保存为 output_gbk.txt")
| 任务 | Python 3 代码 | 说明 |
|---|---|---|
| Unicode 转 GBK | my_str.encode('gbk') |
将字符串编码为 GBK 字节串。 |
| 处理无法编码字符 | my_str.encode('gbk', errors='replace') |
遇到无法编码的字符时,用 替换,避免程序崩溃。 |
| GBK 转 Unicode | my_bytes.decode('gbk') |
将 GBK 字节串解码回字符串。 |
| 写入 GBK 文件 | f.write(my_str.encode('gbk')) |
文件必须以二进制写入模式 ('wb') 打开。 |
在现代 Python 开发(Python 3)中,请始终牢记 str 是文本,bytes 是数据,在程序内部处理时尽量使用 str,只在需要与外部世界(如文件、网络、API)交互时,才使用 .encode() 将其转换为 bytes。
