Python 3中字节转换为字符串的方法

Python 3中字节转换为字符串的方法

技术背景

在Python编程中,字节(bytes)和字符串(str)是两种不同的数据类型。字节对象表示的是二进制数据,而字符串对象表示的是文本数据。在处理文件、网络传输或其他二进制数据时,经常需要将字节对象转换为字符串对象,因此掌握字节到字符串的转换方法是很有必要的。

实现步骤

已知编码类型

如果已知字节对象的编码类型,可以使用decode()方法进行转换。在Python 3中,默认的编码类型是UTF - 8。

1
2
3
b = b"abcde"
string = b.decode("utf-8")
print(string)

未知编码类型

如果不知道字节对象的编码类型,可以使用chardet模块来猜测编码类型,或者使用一些通用的编码如CP437。

1
2
3
4
5
6
7
8
9
10
import sys
PY3K = sys.version_info >= (3, 0)
stream = [b'\x80abc']
lines = []
for line in stream:
if not PY3K:
lines.append(line)
else:
lines.append(line.decode('cp437'))
print(lines)

处理subprocess输出

当处理subprocess的输出时,可以使用以下方法将字节输出转换为字符串。

Python 3.7+

1
2
3
import subprocess
text = subprocess.check_output(["ls", "-l"], text=True)
print(text)

Python 3.6

1
2
3
from subprocess import Popen, PIPE
text = Popen(['ls', '-l'], stdout=PIPE, encoding='utf-8').communicate()[0]
print(text)

核心代码

通用转换方法

1
2
3
4
5
6
7
8
9
10
# 方法1
b = b"abcde"
string1 = b.decode()

# 方法2
import codecs
string2 = codecs.decode(b)

# 方法3
string3 = str(b, encoding="utf-8")

处理可能的解码错误

1
2
bytes = b"abcdefg"
string = bytes.decode("utf-8", "ignore")

编写Pythonic函数

1
2
3
4
5
6
7
def byte_to_str(bytes_or_str):
if isinstance(bytes_or_str, bytes):
print(bytes_or_str.decode('utf-8'))
else:
print("Object not of byte type")

byte_to_str(b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2\n')

处理Windows系统的换行符

1
2
3
Bytes = open("Input.txt", "rb").read()
String = Bytes.decode("utf-8").replace("\r\n", "\n")
open("Output.txt", "w").write(String)

使用json模块自动检测编码

1
2
3
4
import json
b_string = b'test string'
string = b_string.decode(json.detect_encoding(b_string))
print(string)

最佳实践

  • 尽量使用已知的编码类型进行解码,避免使用通用编码如CP437,因为通用编码可能会导致非英语符号的翻译问题。
  • 在处理subprocess输出时,根据Python版本选择合适的方法,优先使用text=True参数。
  • 对于可能出现解码错误的情况,使用errors参数来处理,如ignorebackslashreplace

常见问题

UnicodeDecodeError

当使用错误的编码类型进行解码时,会抛出UnicodeDecodeError。解决方法是使用正确的编码类型,或者使用errors参数来处理错误。

1
2
3
4
5
6
try:
b = b'\x00\x01\xffsd'
string = b.decode('utf-8')
except UnicodeDecodeError:
string = b.decode('utf-8', 'ignore')
print(string)

AttributeError: 'str' object has no attribute 'decode'

在Python 3中,字符串对象没有decode方法。如果尝试对字符串对象调用decode方法,会抛出此错误。解决方法是确保要解码的对象是字节对象。

1
2
3
4
5
6
7
my_str = "Hello World"
# 错误示例
# my_str.decode()

my_byte_str = b'Hello World'
string = str(my_byte_str, 'utf-8')
print(string)

Python 3中字节转换为字符串的方法
https://119291.xyz/posts/2025-05-09.python-3-bytes-to-string-conversion/
作者
ww
发布于
2025年5月9日
许可协议