0

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.

Latot
  • 155
  • 8
  • "_this example don't works and send an error_" If you get an error you should post the logs of it here in the question. – takendarkk Oct 29 '18 at 20:28
  • `eval()` is used in less than <1% of the worlds code *(for a reason)*. If you ever think you need it, what you might want is actually [ast.literal_eval](https://docs.python.org/3/library/ast.html#ast.literal_eval) which is half as harmful but does what you probably think `eval()` will solve. – Torxed Oct 29 '18 at 20:36
  • Hi, i update the post with the error, ast.literal_eval send the same error. – Latot Oct 29 '18 at 20:49
  • Include an example of how you set the value of `data_str`; as it is, it's not clear if you have a 4-byte string or a 7-byte string. – chepner Oct 29 '18 at 20:54
  • Hi, the example of data_str is in the post..., i'll write in the code only in case... – Latot Oct 30 '18 at 22:44

2 Answers2

1

Not sure exactly what you mean, but you could try any 8 bit encoding.

>>> 'Hi\x81y'.encode('latin_1')
b'Hi\x81y'
Håken Lid
  • 22,318
  • 9
  • 52
  • 67
0

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')
nosklo
  • 217,122
  • 57
  • 293
  • 297
  • Hi, this is not what i'm asking, the problem is when we have sores the data of the bytes in a str, and back from there to bytes. – Latot Oct 29 '18 at 20:44