Search code examples
pythonarrayspython-3.xbytecode

convert a string of bytearray to a bytearray


I have a string of bytearray which i want to convert to bytearray in python 3

For example,

x = "\x01\x02\x03\x04"

I get the x variable from server, it is a string but content is byte array, how to convert it to byte array. Really stuck at it. Thanks


Solution

  • You can encode a string to a bytes object and convert that to a bytearray, or convert it directly given some encoding.

    x = "\x01\x02\x03\x04"      # type: str
    y = x.encode()              # type: bytes
    a = bytearray(x.encode())   # type: bytearray
    b = bytearray(x, 'utf-8')   # type: bytearray
    

    Note that bytearray(:str, ...) is specified to use str.encode, so the later two practically do the same. The major difference is that you have to specify the encoding explicitly.