# 验证
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)%256for 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 inlist(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'>