pythoncharacter-encodingiso-8859-1

Convert bytes data inside a string to a true bytes object


In Python 3, I have a string like the following:

mystr = "\x00\x00\x01\x01\x80\x02\xc0\x02\x00"

This string was read from a file and it is the bytes representation of some text. To be clear, this is a unicode string, not a bytes object.

I need to transform mystr into a bytes object like the following:

mybytes = b"\x00\x00\x01\x01\x80\x02\xc0\x02\x00"

Notice that the translation should be literal. I don't want to encode the string.

Running .encode('utf-8') will escape the \.

It I manually copy and past the content into a bytes string, then everything works. What I couldn't find anywhere is how could I convert it without copy+paste.


Solution

  • mystr.encode("latin-1") is what you want.