将字节转换为字符串 [英] Convert bytes to a string

查看:64
本文介绍了将字节转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

<预><代码>>>>从子流程导入 *>>>command_stdout = Popen(['ls', '-l'], stdout=PIPE).communicate()[0]

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

<预><代码>>>>命令标准输出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 字符串处理.这样我就可以像这样打印它:

<预><代码>>>>打印(命令标准输出)-rw-rw-r-- 1 托马斯托马斯 0 Mar 3 07:03 file1-rw-rw-r-- 1 托马斯·托马斯 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 没问题.

解决方案

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

<预><代码>>>>b"abcde"b'abcde'#这里使用utf-8是因为它是一种很常见的编码,但是你# 需要使用您的数据实际使用的编码.>>>b"abcde".decode("utf-8")'ABCDE'

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

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

How do I 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.

解决方案

You need to decode the bytes object to produce a string:

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

这篇关于将字节转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆