Reputation: 75
As a challenge to myself, I wanted to see how I could safely extract a byte literal from inside a regular string. However, I'm not able to safely extract the byte literal out.
Example string:
'b"\\xfeq\\xed\\xad7E\'\\x9a\\xb4_ p\\xdf\\x98\\tC\\xcb\\xe7\\xaa\\x80`\\x93\\x1a\\xf5?\\x03j\\xa4\\x93vT\\xd9"'
Goal:
b"\xfeq\xed\xad7E'\x9a\xb4_ p\xdf\x98\tC\xcb\xe7\xaa\x80`\x93\x1a\xf5?\x03j\xa4\x93vT\xd9"
Upvotes: 0
Views: 52
Reputation: 75
After spending some time going through the documentation, this was the best solution that I could come up with. ast.literal_eval
Is the best way to evaluate literal expressions from untrusted sources. The except
clause is left purposefully broad in order to accommodate for any possible errors.
import ast
def extract_binary_literal(input: str):
try:
result = ast.literal_eval(input)
if type(result) == bytes:
return result
except Exception:
pass
return None
Upvotes: 1