简体   繁体   English

bytearray 到字符串 python2 到 3

[英]bytearray to string python2 to 3

I need to get bytearray as string on python3.我需要在 python3 上将 bytearray 作为字符串获取。 on python 2.7, str(bytearray) results the contents of bytearray in string format.在 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'
    >>>

on python 3.6, even the "bytearray" keyword is added into the resulting string.在 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. why is it happening so on 3.6?为什么在 3.6 上会这样?
  2. how to get the exact same behavior on 3.6 as that of 2.7?如何在 3.6 上获得与 2.7 完全相同的行为? Note: I cannot do c.decode(), as those are compressed/pickled data which will result in invalid start byte errors.注意:我不能执行 c.decode(),因为这些是压缩/腌制数据,会导致无效的起始字节错误。

Any suggestions please.请有任何建议。

The __str__ method for the bytearray class is different in Python 3, to obtain a similar result you could try below snippet. 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