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.

5
  • "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. Commented Oct 29, 2018 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 which is half as harmful but does what you probably think eval() will solve. Commented Oct 29, 2018 at 20:36
  • Hi, i update the post with the error, ast.literal_eval send the same error. Commented Oct 29, 2018 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. Commented Oct 29, 2018 at 20:54
  • Hi, the example of data_str is in the post..., i'll write in the code only in case... Commented Oct 30, 2018 at 22:44

2 Answers 2

1

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

>>> 'Hi\x81y'.encode('latin_1')
b'Hi\x81y'
Sign up to request clarification or add additional context in comments.

1 Comment

Nice!, that its. Thx.
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')

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.