Reputation: 307
i have a string storing data of bytes, an example would be instead have b'Hi\x81y' i have an string with 'Hi\x81y'.
So, with the string, how is in utf-8 i can't read the real data..., and i can't found a way to transform the string expression back to the bytes form.
In some way i'm trying to do this:
data_str = 'Hi\x81y'
eval("b'{}'".format(data_str))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1
SyntaxError: bytes can only contain ASCII literal characters.
Saldy this example don't works and send an error, even worls if we write manually the code .
Any function i test to decode/encode/transform this fails, because python detect the string as utf-8 while is in bytes.
Upvotes: 0
Views: 660
Reputation: 222802
To convert bytes into a string, use the decode
method:
mystring = mybytes.decode('utf-8')
To convert back the string to bytes, use the encode
method:
mybytes = mystring.encode('utf-8')
Upvotes: 0
Reputation: 23064
Not sure exactly what you mean, but you could try any 8 bit encoding.
>>> 'Hi\x81y'.encode('latin_1')
b'Hi\x81y'
Upvotes: 1