《python》 str 和 list 转换 以及eval()函数

python 操作中常对list和字符创的转换进行操作,特此备注。

str –> list

str1 = 'abc'
list1 = list(str1)
list2 = str1.split()
print list1            # ['a','b','c']
print list2            # ['abc']


str2 = 'a b c'
list3 = str2.split(' ')
print list3           # ['a','b','c']

list –> str

l = ['a','b','c']     #注意:l中的元素必须是字符型!
str3 = ''.join(l)
str4 = '.'.join(l)
str5 = ' '.join(l)
print str3                          # abc
print str4                           # a.b.c
print str5                          # a b c
print type(str5)

注意:l中的元素必须是字符型!

help(eval)
eval(…)
eval(source[, globals[, locals]]) -> value

    Evaluate the source in the context of globals and locals.
    The source may be a string representing a Python expression
    or a code object as returned by compile().
    The globals must be a dictionary and locals can be any mapping,
    defaulting to the current globals and locals.
    If only globals is given, locals defaults to it.

官方文档中的解释是,将字符串str当成有效的表达式来求值并返回计算结果。globals和locals参数是可选的,如果提供了globals参数,那么它必须是dictionary类型;如果提供了locals参数,那么它可以是任意的map对象。

a = "[[1,2], [3,4], [5,6], [7,8]]"
b = eval(a)
print b               #[[1, 2], [3, 4], [5, 6], [7, 8]]
print type(b)         # <type 'list'>

a = "{1: 'a', 2: 'b'}"  
b = eval(a)
print b               #{1: 'a', 2: 'b'}
print type(b)         #<type 'dict'>

a = "([1,2], [3,4], [5,6], [7,8])"
b = eval(a)
print b               # ([1, 2], [3, 4], [5, 6], [7, 8])
print type(b)         # <type 'tuple'>

实质就是

a = '1+2'
b = eval(a)
print b
  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值