本文共 1433 字,大约阅读时间需要 4 分钟。
python 操作中常对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']
l = ['a','b','c'] #注意:l中的元素必须是字符型!str3 = ''.join(l)str4 = '.'.join(l)str5 = ' '.join(l)print str3 # abcprint str4 # a.b.cprint str5 # a b cprint type(str5)
注意:l中的元素必须是字符型!
help(eval)
eval(…) eval(source[, globals[, locals]]) -> valueEvaluate 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) #a = "{1: 'a', 2: 'b'}" b = eval(a)print b #{ 1: 'a', 2: 'b'}print type(b) # 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) #
实质就是
a = '1+2'b = eval(a)print b
转载地址:http://aoiqi.baihongyu.com/