將字節(jié)轉換為字符串?我使用這段代碼從外部程序獲得標準輸出:>>> from subprocess import *>>> command_stdout = Popen(['ls', '-l'], stdout=PIPE).communicate()[0]Communications()方法返回一個字節(jié)數(shù)組:>>> command_stdoutb'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我以為這就是b2a_qp()方法,但當我嘗試時,再次得到了相同的字節(jié)數(shù)組:>>> 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'有人知道如何將字節(jié)值轉換回字符串嗎?我是說,用“電池”而不是手工操作。我希望Python 3沒有問題。
4 回答

POPMUISE
TA貢獻1765條經(jīng)驗 獲得超5個贊
您需要解碼字節(jié)對象以生成字符串:
>>> 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'

慕工程0101907
TA貢獻1887條經(jīng)驗 獲得超5個贊
b'hello'.decode(encoding)
str(b'hello', encoding)
添加回答
舉報
0/150
提交
取消