python 列表 字典 string 互相转换

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 编码问题注意点


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值