eval()函数十分强大,官方demo解释为:将字符串str当成有效的表达式来求值并返回计算结果。
可以把字符串转为list、tuple 、dict 等数据类型
1、把字符串转为字典
##############把字符串转为字典##############################
strA ='{"name":"mike","age":10,"sex":"男"}'
dictA = eval(strA)
print type(strA)
print strA
print type(dictA)
print dictA
'''
#结果:
<type 'str'>
{"name":"mike","age":10,"sex":"男"}
<type 'dict'>
{'age': 10, 'name': 'mike', 'sex': '\xe7\x94\xb7'}
'''
2、把字符串转为列表
##############把字符串转为列表##############################
strB ='[["name"],["mike"],["age"],10,"sex","男"]'
listB = eval(strB)
print type(strB)
print strB
print type(listB)
print listB
'''
#结果
<type 'str'>
[["name"],["mike"],["age"],10,"sex","男"]
<type 'list'>
[['name'], ['mike'], ['age'], 10, 'sex', '\xe7\x94\xb7']
'''
3、把字符串转为元组
#####################把字符串转为元组#########################
strC ='(["name"],["mike"],["age"],10,"sex","男")'
tupleC = eval(strC)
print type(strC)
print strC
print type(tupleC)
print tupleC
'''
结果:
<type 'str'>
(["name"],["mike"],["age"],10,"sex","男")
<type 'tuple'>
(['name'], ['mike'], ['age'], 10, 'sex', '\xe7\x94\xb7')
'''