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