Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting python string into bytes directly without eval()

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'?

like image 587
Viewerisland Avatar asked Oct 19 '25 02:10

Viewerisland


1 Answers

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

>>> import ast
>>> stringAsByte = "b'a'"
>>> ast.literal_eval(stringAsByte)
b'a'
like image 128
Jean-François Fabre Avatar answered Oct 22 '25 05:10

Jean-François Fabre



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!