网友问题:
我将外部程序的标准输出捕获到一个对象中:bytes
>>> from subprocess import *
>>> command_stdout = Popen(['ls', '-l'], stdout=PIPE).communicate()[0]
>>>
>>> command_stdout
b'total 0n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2n'
我想将其转换为普通的 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
如何使用 Python 3 将对象转换为对象?bytes
str
网友回答:
这会将字节列表连接成一个字符串:
>>> bytes_data = [112, 52, 52]
>>> "".join(map(chr, bytes_data))
'p44'
网友回答:
解码对象以生成字符串:bytes
>>> b"abcde".decode("utf-8")
'abcde'
上面的示例假定对象采用 UTF-8,因为它是一种常见的编码。但是,您应该使用数据实际使用的编码!bytes
网友回答:
解码字节字符串并将其转换为字符 (Unicode) 字符串。
Python 3:
encoding = 'utf-8'
b'hello'.decode(encoding)
或
str(b'hello', encoding)
Python 2:
encoding = 'utf-8'
'hello'.decode(encoding)
或
unicode('hello', encoding)
模板简介:该模板名称为【我在Python如何将字节转换为字符串】,大小是暂无信息,文档格式为.html,推荐使用Sublime/Dreamweaver/HBuilder打开,作品中的图片,文字等数据均可修改,图片请在作品中选中图片替换即可,文字修改直接点击文字修改即可,您也可以新增或修改作品中的内容,该模板来自用户分享,如有侵权行为请联系网站客服处理。欢迎来懒人模板【Python】栏目查找您需要的精美模板。