不使用eval()将python字符串直接转换为字节 [英] Converting python string into bytes directly without eval()

查看:136
本文介绍了不使用eval()将python字符串直接转换为字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我尝试过执行以下操作以直接转换该字符串(不使用eval):

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'

还有另一个

推荐答案

是,并且 ast.literal_eval 是安全的,因为它仅评估文字

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

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

这篇关于不使用eval()将python字符串直接转换为字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆