1

there!

I have been looking for an answer for quite a bit, but to no avail... Anyway, I had a numpy ndarray and I saved it in a txt file with ndarray.tostring(), so now in my file I have stuff like

"b'\xae\xc9\x91\xff\x9d\x12\xac\xbf\xeasz\xfal\t\xba\xbf\xa18x\xf1\x1bF'"

Now I want to decode that so I can apply ndarray.fromstring(byte_string).

How can I achieve it? I already used bytes(byte_string, 'utf-8'), then decode, removing the b and ', etc...

Thanks a lot!

EDIT: For the record, the solution was using b = ast.literal_eval(byte_string). Thank you, Andy!

1
  • This is not valid utf-8... Commented Nov 8, 2017 at 2:48

2 Answers 2

1

Perhaps you want to decode it directly from bytes:

In [11]: b = b'\xae\xc9\x91\xff\x9d\x12\xac\xbf\xeasz\xfal\t\xba\xbf\xa18x\xf1\x1bF'

In [12]: np.fromstring(b, dtype=np.uint8)
Out[12]:
array([174, 201, 145, 255, 157,  18, 172, 191, 234, 115, 122, 250, 108,
         9, 186, 191, 161,  56, 120, 241,  27,  70], dtype=uint8)
Sign up to request clarification or add additional context in comments.

3 Comments

I say this mainly as this bytes are not valid utf-8 (they don't decode)
The issue is that in the text file is already saved as "b'\xae\xc9\x91\xff\x9d\x12\xac\xbf\xeasz\xfal\t\xba\xbf\xa18x\xf1\x1bF'", so when I save it in a variable, it doesn't store it as a BYTES object, but a string.
@david you can read it as bytes with b = ast.literal_eval(open(file_name).read())
1

Your string is BYTE object. str(b'','utf8')

2 Comments

I believe it should be utf-8
The issue is that in the text file is already saved as "b'\xae\xc9\x91\xff\x9d\x12\xac\xbf\xeasz\xfal\t\xba\xbf\xa18x\xf1\x1bF'", so when I save it in a variable, it doesn't store it as a BYTES object, but a string.

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.