简体   繁体   中英

bytearray to string python2 to 3

I need to get bytearray as string on python3. on python 2.7, str(bytearray) results the contents of bytearray in string format.

    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.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?
  2. how to get the exact same behavior on 3.6 as that of 2.7? Note: I cannot do c.decode(), as those are compressed/pickled data which will result in invalid start byte errors.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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