python 列表 字典 string 互相转换

来源:互联网 发布:流星网络电视 apk 编辑:程序博客网 时间:2024/05/16 10:17

1: dict 转为 string   使用str方法

<span style="font-size:18px;">a = {1: 'a', 2: 'b'}a = str(a)print a, type(a)-----{1: 'a', 2: 'b'} <type 'str'></span>

2: string 转为 dict  使用eval方法

<span style="font-size:18px;">a = "{1: 'a', 2: 'b'}"a = eval(a)print a, type(a)------{1: 'a', 2: 'b'} <type 'dict'></span>

3: list 转为string  使用join方法, 单引号内为字符连接的符号, 可以为空,也可以为 '-' 等符号

<span style="font-size:18px;">a = ['hello', 'world']b = ' '.join(a)print b, type(b)c= '-'.join(a)print c, type(c)----hello world <type 'str'>hello-world <type 'str'></span>

4: string 转为 list  这个就很方便了,使用split函数,参数为分隔符,可以为空

<span style="font-size:18px;">a = u'hello world'b = a.split(' ')print b, type(b)c = a.split('o')print c, type(c)-------[u'hello', u'world'] <type 'list'>[u'hell', u' w', u'rld'] <type 'list'></span>

关于string前面的u, 在python2.x中,对字符的兼容还不是很好, 使用3.x 问题不大.   养成一个良好的习惯, 在string前面加一个u, 会省去很多编码问题. 如果你有编码问题,可以参阅这篇文章,写的很好.

python 编码问题注意点


0 0
原创粉丝点击