gpt4 book ai didi

python - 将字节转换为字符串

转载 作者:bug小助手 更新时间:2023-10-28 01:27:52 28 4
gpt4 key购买 nike

我将外部程序的标准输出捕获到 bytes 对象中:

>>> 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

我试过 binascii.b2a_qp()方法,但又得到了相同的 bytes 对象:

>>> binascii.b2a_qp(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 3 将 bytes 对象转换为 str

最佳答案

Decode the bytes object产生一个字符串:

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

上面的例子假设 bytes 对象是UTF-8,因为它是一种常见的编码。但是,您应该使用数据实际所在的编码!

关于python - 将字节转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/606191/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com