相关疑难解决方法(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 中将整数列表转换为字节数组

我是 Python 的新手(C 是我的主要语言),所以这可能是一个超级基本/幼稚的问题。

我有两个使用以下 Python 代码生成的整数列表:

mainList = range(100)
random.shuffle(mainList)
list1 = mainList[:len(mainList)/2]
list2 = mainList[len(mainList)/2:]
Run Code Online (Sandbox Code Playgroud)

基本上,我试图通过 TCP 连接发送这些列表(list1list2)中的每一个,并且我想确保我只为每个列表发送 50 字节的有效负载(每个列表包含 50 个整数)。

什么是最好的方法来做到这一点?该bytearray()功能是否适用于这里?

python bytearray list python-2.7 python-3.x

2
推荐指数
1
解决办法
5245
查看次数

标签 统计

python ×2

python-3.x ×2

bytearray ×1

list ×1

python-2.7 ×1

string ×1