Python2.7中的几种集合类型转换

bytes就是str, 不用转换

# 验证
In [1]: type(bytes()) == type(str())
Out[1]: True

str转unicode

# 定义一个str字符串
In [1]: s = '你好啊'
In [2]: print s, type(s)
你好啊 <type 'str'>

#方法1
In [3]: u = s.decode(encoding='utf-8')
In [4]: print u, type(u)
你好啊 <type 'unicode'>

# 方法2
In [5]: u = unicode(s, encoding='utf-8')
In [6]: print u, type(u)
你好啊 <type 'unicode'>

unicode 转 str

# 定义一个unicode字符串
In [1]: u = u'你好'
In [2]: print u, type(u)
你好 <type 'unicode'>

# 方法1
In [3]: s = u.encode(encoding='utf-8')
In [4]: print s, type(s)
你好 <type 'str'>

# 方法2
In [5]: s = unicode.encode(u, encoding='utf-8')
In [6]: print s, type(s)
你好 <type 'str'>

tuple转list

# 定义一个tuple
In [1]: t = (1, 2, 3)
In [2]: print t, type(t)
(1, 2, 3) <type 'tuple'>

# 方法1
In [3]: l = list(t)
In [4]: print l, type(l)
[1, 2, 3] <type 'list'>

# 方法2
In [5]: l = [ i for i in t]
In [6]: print l, type(l)
[1, 2, 3] <type 'list'>

list转tuple

#定义一个list
In [1]: l = [1, 2, 3, 4]
In [2]: print l, type(l)
[1, 2, 3, 4] <type 'list'>

# 方法 
In [3]: t = tuple(l)
In [4]: print t, type(t)
(1, 2, 3, 4) <type 'tuple'>

## 注意: 此时t = (i for i in l)的结果可不是tuple, 而是一个generator, 通过调用next()来获得每一个值)

字节(-128 ~ 127) list (tuple) 转字符串 (接收来自其他语言传递的中文字符串时很常见, 如ros)

# 定义一个 字节list
In [1]: l = [-28, -67, -96, -27, -91, -67, -27, -107, -118, -212, -224, -26, -120, -111, -26, -104, -81, -28, -67, -96, -25, -120, -72, -25, -120, -72]
# In [1]: l = (-28, -67, -96, -27, -91, -67, -27, -107, -118, -212, -224, -26, -120, -111, -26, -104, -81, -28, -67, -96, -25, -120, -72, -25, -120, -72)
# to str
In [2]: import array
In [3]: s = array.array('B', [(i + 256) % 256 for i in l]).tostring()
In [4]: print s, type(s)
你好啊, 我是你爸爸 <type 'str'>
In [5]: s = str(bytearray(l))
In [6]: print s, type(s)
你好啊, 我是你爸爸 <type 'str'>

str 转 字节list

# 定义一个中文字符串
In [1]: s = '你好,猜猜我是谁'
# 转为 字节list
In [2]: l = [ord(i) for i in list(s)]
In [3]: print l, type(l)
[228, 189, 160, 229, 165, 189, 239, 188, 140, 231, 140, 156, 231, 140, 156, 230, 136, 145, 230, 152, 175, 232, 176, 129] <type 'list'>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值