Convert bytes to a string?

I'm using this code to get standard output from an external program:

>>> from subprocess import *
>>> command_stdout = Popen(['ls', '-l'], stdout=PIPE).communicate()[0]

The communicate() method returns an array of bytes:

>>> command_stdout
b'total 0n-rw-rw-r-- 1 thomas thomas 0 Mar  3 07:03 file1n-rw-rw-r-- 1 thomas thomas 0 Mar  3 07:03 file2n'

However, I'd like to work with the output as a normal Python string. So that I could print it like this:

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

I thought that's what the binascii.b2a_qp() method is for, but when I tried it, I got the same byte array again:

>>> binascii.b2a_qp(command_stdout)
b'total 0n-rw-rw-r-- 1 thomas thomas 0 Mar  3 07:03 file1n-rw-rw-r-- 1 thomas thomas 0 Mar  3 07:03 file2n'

Does anybody know how to convert the bytes value back to string? I mean, using the "batteries" instead of doing it manually. And I'd like it to be ok with Python 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 = [112, 52, 52]
"".join(map(chr, bytes))
>> p44

You need to decode the byte string and turn it in to a character (unicode) string.

b'hello'.decode(encoding)

or

str(b'hello', encoding)
链接地址: http://www.djcxy.com/p/3548.html

上一篇: 如何在Java中检查字符串是否为数字

下一篇: 将字节转换为字符串?