Converting python string into bytes directly without eval()

ⅰ亾dé卋堺 提交于 2019-12-04 05:19:47

问题


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:


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

>>> import ast
>>> stringAsByte = "b'a'"
>>> ast.literal_eval(stringAsByte)
b'a'


来源:https://stackoverflow.com/questions/51775126/converting-python-string-into-bytes-directly-without-eval

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!