繁体   English   中英

bytearray 到字符串 python2 到 3

[英]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')"
    >>>
  1. 为什么在 3.6 上会这样?
  2. 如何在 3.6 上获得与 2.7 完全相同的行为? 注意:我不能执行 c.decode(),因为这些是压缩/腌制数据,会导致无效的起始字节错误。

请有任何建议。

bytearray class 的__str__方法与 Python 不同 3,要获得类似的结果,您可以尝试下面的代码片段。

>>> str(bytes(c))
"b'\\x80\\x04\\x95h\\x00\\x00'"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM