[英]bytearray to string python2 to 3
我需要在 python3 上将 bytearray 作为字符串获取。 在 python 2.7 上,str(bytearray) 以字符串格式生成 bytearray 的内容。
Python 2.7.18 (default, Feb 8 2022, 09:11:29)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-44)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> c = bytearray(b'\x80\x04\x95h\x00\x00')
>>> str(c)
'\x80\x04\x95h\x00\x00'
>>>
在 python 3.6 上,甚至将“bytearray”关键字添加到结果字符串中。
Python 3.6.8 (default, Aug 12 2021, 07:06:15)
[GCC 8.4.1 20200928 (Red Hat 8.4.1-1)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> c = bytearray(b'\x80\x04\x95h\x00\x00')
>>> str(c)
"bytearray(b'\\x80\\x04\\x95h\\x00\\x00')"
>>>
请有任何建议。
bytearray
class 的__str__
方法与 Python 不同 3,要获得类似的结果,您可以尝试下面的代码片段。
>>> str(bytes(c))
"b'\\x80\\x04\\x95h\\x00\\x00'"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.