博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
《python》 str 和 list 转换 以及eval()函数
阅读量:4230 次
发布时间:2019-05-26

本文共 1433 字,大约阅读时间需要 4 分钟。

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                          # abcprint str4                           # a.b.cprint str5                          # a b cprint 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)         # 
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/

你可能感兴趣的文章
Rails for Java Developers [ILLUSTRATED]
查看>>
LINQ: The Future of Data Access in C# 3.0
查看>>
Everyday Scripting with Ruby: For Teams, Testers, and You [ILLUSTRATED]
查看>>
Beginning Excel Services
查看>>
Professional Rich Internet Applications: AJAX and Beyond
查看>>
Foundations of PEAR: Rapid PHP Development
查看>>
LINQ for Visual C# 2005
查看>>
LINQ for VB 2005
查看>>
Practical Subversion, Second Edition
查看>>
Essential MATLAB for Engineers and Scientists, Third Edition
查看>>
Pro SMS 2003
查看>>
Cisco: A Beginner's Guide, Fourth Edition (Beginner's Guide
查看>>
Google Earth For Dummies
查看>>
Adobe Acrobat 8 for Windows and Macintosh: Visual QuickStart Guide
查看>>
Maya Professional Tips and Techniques
查看>>
PowerPoint 2007 Just the Steps For Dummies
查看>>
Wireless Networking Technology: From Principles to Successful Implementation
查看>>
Mining Graph Data
查看>>
JavaScript Bible
查看>>
Programmer's Guide to NCurses
查看>>