将字节转换为字符串

2024-04-19 17:28:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用此代码从外部程序获取标准输出:

>>> 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()方法的作用,但当我尝试它时,我又得到了相同的字节数组:

>>> 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可以使用它。


Tags: 方法字符串字节stdoutthomas数组file1mar
3条回答

需要解码bytes对象以生成字符串:

>>> b"abcde"
b'abcde'

# utf-8 is used here because it is a very common encoding, but you
# need to use the encoding your data is actually in.
>>> b"abcde".decode("utf-8") 
'abcde'

我觉得这样很简单:

bytes_data = [112, 52, 52]
"".join(map(chr, bytes_data))
>> p44

您需要解码字节字符串并将其转换为字符(Unicode)字符串。

关于Python 2

encoding = 'utf-8'
'hello'.decode(encoding)

或者

unicode('hello', encoding)

在Python 3上

encoding = 'utf-8'
b'hello'.decode(encoding)

或者

str(b'hello', encoding)

相关问题 更多 >