1. 程式人生 > >《python》 str 和 list 轉換 以及eval()函式

《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