首页 > 代码库 > python-eval、repr函数

python-eval、repr函数

eval函数将字符串当成有效Python表达式来求值,并返回计算结果 

string+  eval==》list,tuple,dict

repr + list,tuple,dict ==》string
#################################################
字符串转换成列表
>>>a = "[[1,2], [3,4], [5,6], [7,8], [9,0]]"
>>>type(a)
<type ‘str‘>
>>> b = eval(a)
>>> print b
[[1, 2], [3, 4], [5, 6], [7, 8], [9, 0]]
>>> type(b)
<type ‘list‘>
#################################################
字符串转换成字典
>>> a = "{1: ‘a‘, 2: ‘b‘}"
>>> type(a)
<type ‘str‘>
>>> b = eval(a)
>>> print b
{1: ‘a‘, 2: ‘b‘}
>>> type(b)
<type ‘dict‘>
#################################################
字符串转换成元组
>>> a = "([1,2], [3,4], [5,6], [7,8], (9,0))"
>>> type(a)
<type ‘str‘>
>>> b = eval(a)
>>> print b
([1, 2], [3, 4], [5, 6], [7, 8], (9, 0))
>>> type(b)
<type ‘tuple‘>

 

 

 

---------------------------------

Python Cookbook 3rd Edition Documentation — python3-cookbook 2.0.0 文档
http://python3-cookbook.readthedocs.io/zh_CN/latest/

python-eval、repr函数