0

I have a string like this: s = "b'1f\xe6\xb5\x8b\xe7\xbb\x98'"

How to convert it back to the original string?

I try to use eval(s), however get SyntaxError: bytes can only contain ASCII literal characters.

5
  • 1
    Have you tried decoding s using s.decode('utf-8')? Commented Jul 5, 2018 at 12:03
  • 3
    If a string prints as "b'1f\xe6\xb5\x8b\xe7\xbb\x98'", you have to double the backslashes if you're trying to test it in console: eval("b'1f\\xe6\\xb5\\x8b\\xe7\\xbb\\x98'").decode('utf-8') gives a possibly useful result. The problem is that your original is just a fragment, so you get something like '1f测绘', where 1f is an orphan of cut-and-paste or something. How did you end up with that string? It would be better to take it closer to the source where it was less mangled. Commented Jul 5, 2018 at 12:05
  • @Gsk I'll rather upvote FHTMitchell :) Commented Jul 5, 2018 at 12:12
  • It's just a test text file encoded with Huffman Coding. I convert all text to byte to get them coded. And I want to decode it. "b'1f\xe6\xb5\x8b\xe7\xbb\x98'" is the decoded result which is the byte formatted text of original text '1f测绘'. Commented Jul 5, 2018 at 12:18
  • No, b'1f\xe6\xb5\x8b\xe7\xbb\x98' is. In your question, it is additionally wrapped in a string, which complicates everything unnecessarily. If you just have the bytes, you wouldn't need to evaluate the string first. Commented Jul 6, 2018 at 3:40

1 Answer 1

2

Don't use eval, it's dangerous. Use ast.literal_eval instead and then decode to a string like @Amadan says:

import ast
s = r"b'1f\xe6\xb5\x8b\xe7\xbb\x98'"
res = ast.literal_eval(s).decode()
print(res)  # --> '1f测绘'

As is said in the comments, my s actually has a repr that looks like "b'1f\\xe6\\xb5\\x8b\\xe7\\xbb\\x98'". Can you please confirm what your print(repr(your_string)) and print(your_string) look like?

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much! I confirm that s = "b'1f\xe6\xb5\x8b\xe7\xbb\x98'" is what I got.

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.