Convert bytes data inside a string to a true bytes object
Question:
In Python 3, I have a string like the following:
mystr = "x00x00x01x01x80x02xc0x02x00"
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"x00x00x01x01x80x02xc0x02x00"
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.
Answers:
mystr.encode("latin-1")
is what you want.
In Python 3, I have a string like the following:
mystr = "x00x00x01x01x80x02xc0x02x00"
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"x00x00x01x01x80x02xc0x02x00"
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.
mystr.encode("latin-1")
is what you want.