ShenLei ShenLei - 5 months ago 22
Python Question

What is the invert operation of bytes repr() in python3?

a = b'\x00\x01'
ra = repr(a) # ra == "b'\\x00\\x01'"
assert invert_repr(ra) == a


What is the correct form of invert_repr? string_escape & unicode_escape?

Answer

Use eval or equivalent:

from ast import literal_eval
a = b'\x00\x01'
ra = repr(a)
assert literal_eval(ra) == eval(ra) == a # no error

ast.literal_eval is safer than eval.