python基础:eval函数妙用--将字符串str转换成列表、字典等

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

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

  参数:

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

    globals:可选。必须是dictionary

    locals:可选。任意map对象

  实例展示:

复制代码
 1 可以把list,tuple,dict和string相互转化。
 2 #################################################
 3 字符串转换成列表  4 >>>a = "[[1,2], [3,4], [5,6], [7,8], [9,0]]"  5 >>>type(a)  6 <type 'str'>  7 >>> b = eval(a)  8 >>> print b  9 [[1, 2], [3, 4], [5, 6], [7, 8], [9, 0]] 10 >>> type(b) 11 <type 'list'> 12 ################################################# 13 字符串转换成字典 14 >>> a = "{1: 'a', 2: 'b'}" 15 >>> type(a) 16 <type 'str'> 17 >>> b = eval(a) 18 >>> print b 19 {1: 'a', 2: 'b'} 20 >>> type(b) 21 <type 'dict'> 22 ################################################# 23 字符串转换成元组 24 >>> a = "([1,2], [3,4], [5,6], [7,8], (9,0))" 25 >>> type(a) 26 <type 'str'> 27 >>> b = eval(a) 28 >>> print b 29 ([1, 2], [3, 4], [5, 6], [7, 8], (9, 0)) 30 >>> type(b) 31 <type 'tuple'>
复制代码

转载于:https://www.cnblogs.com/yizhenfeng168/p/6934222.html

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值