python重要函数eval多种用法解析

yipeiwu_com6年前Python基础

这篇文章主要介绍了python重要函数eval多种用法解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

1.参数会作为一个 Python 表达式(从技术上说是一个条件列表)被解析并求值

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

2.去除字符串两边的引号

>>> a='"srting"'
>>> print(a)
"srting"
>>> b=eval(a)
>>> print(b)

srting

也可以用

>>> a.strip('"')
'srting'

3.字符串转字典

>>> a= "{'name':'linux','age':18}"
>>> type(a)
<type 'str'>
>>> b=eval(a)
>>> b
{'age': 18, 'name': 'linux'}
>>> type(b)
<type 'dict'>

4.传递全局变量

>>> a= "{'name':'linux','age':age}"
>>> b=eval(a,{"age":1822})
>>> b
{'age': 1822, 'name': 'linux'}
>>> type(b)
<type 'dict'>

5.传递本地变量

>>> a= "{'name':'linux','age':age}"
>>> age=18
>>> b=eval(a,{"age":1822},locals())
>>> b
{'age': 18, 'name': 'linux'}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python实现斐波那契数列的方法示例

python实现斐波那契数列的方法示例

介绍 斐波那契数列,又称黄金分割数列,指的是这样一个数列:0、1、1、2、3、5、8、13、21、……在数学上,斐波纳契数列以如下递归的方法定义: F(0)=0,F(1)=1,F(n)=...

Python version 2.7 required, which was not found in the registry

Python version 2.7 required, which was not found in the registry

安装PIL库的时候,直接提示:Python version 2.7 required, which was not found in the registry。 如图: 大意是说找不到...

Python实现判断字符串中包含某个字符的判断函数示例

Python实现判断字符串中包含某个字符的判断函数示例

本文实例讲述了Python实现判断字符串中包含某个字符的判断函数。分享给大家供大家参考,具体如下: #coding=utf8 #参数包含两个: #containVar:查找包含的字符...

python根据list重命名文件夹里的所有文件实例

如下所示: # coding = utf-8 import os path = "D:\\chunyu"#想要重命名所有文件存放的文件夹 filelist = os.listdir(...

python MNIST手写识别数据调用API的方法

python MNIST手写识别数据调用API的方法

MNIST数据集比较小,一般入门机器学习都会采用这个数据集来训练 下载地址:yann.lecun.com/exdb/mnist/ 有4个有用的文件: train-images-idx3...