4

eval() seems to be dangerous to use when processing unknown strings, which is what a part of my project is doing.

For my project I have a string, called:

stringAsByte = "b'a'"

I've tried to do the following to convert that string directly (without using eval):

byteRepresentation = str.encode(stringAsByte)
print(byteRepresentation) # prints b"b'a'"

Clearly, that didn't work, so instead of doing:

byteRepresentation = eval(stringAsByte) # Uses eval!

print(byteRepresentation) # prints b'a'

Is there another way where I can get the output b'a'?

1 Answer 1

9

yes, with ast.literal_eval which is safe since it only evaluates literals.

>>> import ast
>>> stringAsByte = "b'a'"
>>> ast.literal_eval(stringAsByte)
b'a'
Sign up to request clarification or add additional context in comments.

Comments

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.