您的位置:首页 > 编程语言 > Python开发

python 列表 字典 string 互相转换

2014-09-16 21:52 721 查看
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 编码问题注意点
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python