Python中eval()函数的功能及使⽤⽅法
eval(str)函数很强⼤,官⽅解释为:将字符串str当成有效的表达式来求值并返回计算结果。所以,结合math当成⼀个计算器很好⽤。eval()函数常见作⽤有:
1、计算字符串中有效的表达式,并返回结果
>>> eval('pow(2,2)')
4
>>> eval('2 + 2')
4
>>> eval("n + 4")
85
2、将字符串转成相应的对象(如list、tuple、dict和string之间的转换)
将python内存中的数据类型转成其该有的数据类型,⽽不是json字符串
>>> a = "[[1,2], [3,4], [5,6], [7,8], [9,0]]"
>>> b = eval(a)
>>> b
[[1, 2], [3, 4], [5, 6], [7, 8], [9, 0]]
>>> a = "{1:'xx',2:'yy'}"
>>> c = eval(a)
>>> c
{1: 'xx', 2: 'yy'}
>>> a = "(1,2,3,4)"
>>> d = eval(a)
>>> d
(1, 2, 3, 4)
例外:json格式的字典字符串如果键值对中的值为单字节的话可以使⽤eval()表达式转换为python数据类型【例如json转dict】
①但是如果json格式的字典字符串中的键值对中的值为复杂的数据类型如列表或者列表中嵌套字典则⽆法将json转换为dict数据
②eval(str)当字符串中有null【null的反序列化通过json.load()⽅法可以转换为None】值,⽆法将字符串转成相应的对象,会报错。json_string = """{
"answerList": [
{
"content": "string",
"questionId": "string",
"questionIndex": 0,
"questionTitle": "string",
"questionType": 0,
"questionWeight": 0,
"score": 0,
"scoreId": "string",
"scoreName": "string",
"scoreWeight": 0,
"selectOptions": [
{
"disabledWeight": true,
"evaluateStatus": 0,
"optionId": "string",
"optionTitle": "string",
"optionWeight": 0
}
],
"tags": [
{
"tagId": "string",
"tagTitle": "string"
}
]
python index函数
}
],
"channel": "string",
"externalUnionid": "string",
"key": "string",
"qaJson": "string",
"unionid": "string",
"uuid": "string"
}"""
print(json_string) #打印json字符串
print(type(json_string))#打印json字符串的类型:str
print(eval(json_string))使⽤eval()表达式把json字符串转换为python数据类型:字典类型--》结果失败,报错
json_dict = json.loads(json_string) #使⽤json.loads反序列化⽅式,将json字符串转换为python数据类型成功print(type(json_dict)) #打印转换后的数据类型:dict
print(json_dict)#打印转换成功后的字典数据
3、将利⽤反引号转换的字符串再反转回对象
>>> list1 = [1,2,3,4,5]
>>> `list1`
'[1, 2, 3, 4, 5]'
>>> type(`list1`)
<type 'str'>
>>> type(eval(`list1`))
<type 'list'>
>>> a = eval(`list1`)
>>> a
[1, 2, 3, 4, 5]