我将外部程序的标准输出捕获到一个字节对象中:

>>> from subprocess import *
>>> command_stdout = Popen(['ls', '-l'], stdout=PIPE).communicate()[0]
>>>
>>> command_stdout
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'

我想把它转换成一个普通的Python字符串,这样我就可以这样打印了:

>>> print(command_stdout)
-rw-rw-r-- 1 thomas thomas 0 Mar  3 07:03 file1
-rw-rw-r-- 1 thomas thomas 0 Mar  3 07:03 file2

如何使用Python 3将字节对象转换为str?


当前回答

解码字节对象以生成字符串:

>>> b"abcde".decode("utf-8") 
'abcde'

上面的示例假设字节对象是UTF-8格式的,因为它是一种常见的编码。但是,您应该使用数据实际使用的编码!

其他回答

解码字节对象以生成字符串:

>>> b"abcde".decode("utf-8") 
'abcde'

上面的示例假设字节对象是UTF-8格式的,因为它是一种常见的编码。但是,您应该使用数据实际使用的编码!

虽然@Aaron Maenpaa的回答很有效,但一位用户最近问道:

还有什么更简单的方法吗?”fhand.read().decode(“ASCII”)'[…]太长了!

您可以使用:

command_stdout.decode()

decode()有一个标准参数:

codec.decode(obj,编码='utf-8',错误='strict')

试试看:

bytes.fromhex('c3a9').decode('utf-8') 

使用Windows系统中的数据(以行结尾)时,我的答案是

String = Bytes.decode("utf-8").replace("\r\n", "\n")

为什么?尝试使用多行Input.txt:

Bytes = open("Input.txt", "rb").read()
String = Bytes.decode("utf-8")
open("Output.txt", "w").write(String)

所有的行尾都将加倍(到\r\n),导致多余的空行。Python的文本读取函数通常规范化行结尾,以便字符串只使用\n。如果您从Windows系统接收二进制数据,Python就没有机会这样做。因此

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

将复制原始文件。

如果您应该通过尝试decode()获得以下结果:

AttributeError:“str”对象没有属性“decode”

也可以直接在转换中指定编码类型:

>>> my_byte_str
b'Hello World'

>>> str(my_byte_str, 'utf-8')
'Hello World'