ringsaturn
ringsaturn

Reputation: 99

convert byte text( type is string) to string in python

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.

Upvotes: 0

Views: 827

Answers (1)

FHTMitchell
FHTMitchell

Reputation: 12157

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?

Upvotes: 2

Related Questions