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.
1 Answer 1
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?
answered Jul 5, 2018 at 12:12
FHTMitchell
12.2k2 gold badges40 silver badges50 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
ringsaturn
Thank you very much! I confirm that
s = "b'1f\xe6\xb5\x8b\xe7\xbb\x98'" is what I got.lang-py
susings.decode('utf-8')?"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测绘', where1fis 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."b'1f\xe6\xb5\x8b\xe7\xbb\x98'"is the decoded result which is the byte formatted text of original text '1f测绘'.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.