我将外部程序的标准输出捕获到一个字节对象中:
>>> 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?
我们可以使用bytes.decode(encoding='utf-8',errors='strict')对bytes对象进行解码以生成字符串。有关文档,请参阅bytes.decode。
Python 3示例:
byte_value = b"abcde"
print("Initial value = {}".format(byte_value))
print("Initial value type = {}".format(type(byte_value)))
string_value = byte_value.decode("utf-8")
# utf-8 is used here because it is a very common encoding, but you need to use the encoding your data is actually in.
print("------------")
print("Converted value = {}".format(string_value))
print("Converted value type = {}".format(type(string_value)))
输出:
Initial value = b'abcde'
Initial value type = <class 'bytes'>
------------
Converted value = abcde
Converted value type = <class 'str'>
注意:在Python 3中,默认情况下编码类型为UTF-8。因此,<byte_string>.decode(“utf-8”)也可以写成<byte-string>.decode()