python2和python3的encode、decode

  • python3默认编码unicode,python2默认编码ascii
  • python2中的编码是ascii 需要decode() 变更成unicode在encode()操作
  • python3的基础编码unicode直接可以encode()操作

python3的encode()、decode()

# python3默认编码unicode  在Python3中,str中存储的是一系列unicode码字 如果仍要处理一系列bytes字符串,则需要在字符串直接量前面加 b 前缀。这种情况下你将会得到一个bytes类型的对象
# bytes转化为字符串
In [18]: b = b'hello world!'
In [19]: type(b)
Out[19]: bytes
In [20]: a = b.decode()
In [21]: a
Out[21]: 'hello world!'
In [22]: type(a)
Out[22]: str

# 字符串转化为bytes
In [23]: a ="我爱你!"
In [24]: type(a)
Out[24]: str
In [25]: b = a.encode()
In [26]: type(b)
Out[26]: bytes
In [27]: b
Out[27]: b'\xe6\x88\x91\xe7\x88\xb1\xe4\xbd\xa0\xef\xbc\x81'
In [28]: b.decode()
Out[28]: '我爱你!'

python2的encode()、decode()

# python2默认编码ascii (美国标准信息交换码(The American Standard Code for Information Interchange))
# ASCII事实上就是把一系列常用的字符与一系列数字码点(code point)(从0到127)对应了起来。比如小写的’a’就表示为97,也就是二进制0110001。由于ASCII由美国人制定,只考虑到了英语字符,所以无法表示其他语言中的字符
  • unicode.encode() -> bytes:只有对于unicode对象我们才应该使用.encode()方法。这一方法用来将一系列unicode编码为bytes流。
  • bytes.decode() -> unicode: 只有对于bytes,或说Python2中的str对象,我们才应该调用.decode()方法。这一方法将一系列bytes流解码为原本的unicode码点。
# 1.字符串转为unicode
>>> a = 'hello'
>>> type(a)
<type 'str'>
>>> b=a.decode()
>>> type(b)
<type 'unicode'>


# 2.unicode 转化为str
>>> b = u'我爱你!'
>>> type(b)
<type 'unicode'>
>>> a = b.encode("utf-8")
>>> a
'\xe6\x88\x91\xe7\x88\xb1\xe4\xbd\xa0\xef\xbc\x81'
>>> type(a)
<type 'str'>
>>> c = a.decode('utf-8')
>>> c
u'\u6211\u7231\u4f60\uff01'
>>> type(c)
<type 'unicode'>

>>> d = c.encode('utf-8')
>>> d
'\xe6\x88\x91\xe7\x88\xb1\xe4\xbd\xa0\xef\xbc\x81'
>>> print(d)
我爱你!
>>> 

>>> a =u'hello'
>>> b = a.encode("gbk")
>>> b
'hello'
>>> type(b)
<type 'str'>
>>> b.decode('utf-8')
u'hello'
>>> c =b.decode('utf-8')
>>> type(c)
<type 'unicode'>
>>>
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值