Python eval 函数妙用

2023-07-29,,

eval

功能:将字符串str当成有效的表达式来求值并返回计算结果。

语法: eval(source, globals, locals) -> value

参数:

source:一个Python表达式或函数compile()返回的代码对象

globals:可选。必须是dictionary

locals:可选。任意map对象

实例展示:

可以把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'>

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

x = 1
eval('x+1')
eval('x==1')

与之对应的repr函数,它能够将Python的变量和表达式转换为字符串表示

repr(x==1)
repr(x+1)

Python eval 函数妙用的相关教程结束。

《Python eval 函数妙用.doc》

下载本文的Word格式文档,以方便收藏与打印。