'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')"
>>>
- why is it happening so on 3.6 ?
- 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.
Solution 1:[1]
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'"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Piotr Ostrowski |
