将字节转换为字符串

新手上路,请多包涵

我将外部程序的标准输出捕获到 bytes 对象中:

 >>> from subprocess import *
>>> command_stdout = Popen(['ls', '-l'], stdout=PIPE).communicate()[0]
>>>
>>> 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 字符串,这样我就可以像这样打印它:

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

我尝试了 binascii.b2a_qp() 方法,但又得到了相同的 bytes 对象:

 >>> 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 对象转换为 str

原文由 Tomas Sedovic 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 833
2 个回答

解码 bytes 对象 以生成字符串:

 >>> b"abcde".decode("utf-8")
'abcde'

上面的例子 假设 bytes 对象是 UTF-8,因为它是一种常见的编码。但是,您应该使用数据实际所在的编码!

原文由 Aaron Maenpaa 发布,翻译遵循 CC BY-SA 4.0 许可协议

解码字节字符串并将其转换为字符 (Unicode) 字符串。


蟒蛇 3:

 encoding = 'utf-8'
b'hello'.decode(encoding)

要么

str(b'hello', encoding)


蟒蛇2:

 encoding = 'utf-8'
'hello'.decode(encoding)

要么

unicode('hello', encoding)

原文由 dF. 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题