相关疑难解决方法(0)

将字节转换为字符串?

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

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

communic()方法返回一个字节数组:

>>> 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'
Run Code Online (Sandbox Code Playgroud)

但是,我想将输出作为普通的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
Run Code Online (Sandbox Code Playgroud)

我认为这是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'
Run Code Online (Sandbox Code Playgroud)

有人知道如何将字节值转换回字符串吗?我的意思是,使用"电池"而不是手动操作.而且我希望它能用于Python 3.

python string python-3.x

1968
推荐指数
18
解决办法
203万
查看次数

将字节字符串拆分为行

如何将字节字符串拆分为行列表?

在python 2我有:

rest = "some\nlines"
for line in rest.split("\n"):
    print line
Run Code Online (Sandbox Code Playgroud)

上面的代码是为了简洁起见而简化的,但现在经过一些正则表达式处理后,我有一个字节数组rest,我需要迭代这些行.

python python-3.x

40
推荐指数
3
解决办法
5万
查看次数

标签 统计

python ×2

python-3.x ×2

string ×1