Python 学习笔记(十二)

编码和解码流程图

这里写图片描述

unicode 编码转换成 utf-8gbk 的过程叫做编码,将 utf-8 还原成 unicode 的过程叫做解码

Python3

# python3
In [1]: s1 = "你好,中文"
In [2]: s1
Out[2]: '你好,中文'
In [3]: s2 = s1.encode("utf-8")
In [4]: s2
Out[4]: b'\xe4\xbd\xa0\xe5\xa5\xbd\xef\xbc\x8c\xe4\xb8\xad\xe6\x96\x87'
In [5]: s3 = s2.decode("utf-8")
In [6]: s3
Out[6]: '你好,中文'

Python3 中,文本字符串类型 (unicode) 被命名为 str,字节字符串类型被命名为bytes,python3 默认是 unicode编码,如果想得到 bytes 类型,可以在字符串前加上前缀b,或者 encode 一下。

>>> string = "你好,中文"
>>> type(string)
<class 'str'>
>>>
>>> s2 = b'hello'
>>> type(s2)
<class 'bytes'>
>>>
>>> string.encode('utf-8')
b'\xe4\xbd\xa0\xe5\xa5\xbd\xef\xbc\x8c\xe4\xb8\xad\xe6\x96\x87'
>>>

str 对象有一个 encode() 方法,bytes 对象有一个 decode() 方法

Python2

>>> s1 = '中文'
>>> s1
>>>'\xe4\xb8\xad\xe6\x96\x87'
>>> type(s1)
<type 'str'>
>>> s2 = s1.decode('utf-8')
>>> s2
u'\u4e2d\u6587'
>>> type(s2)
<type 'unicode'>
>>> s3 = s2.encode('utf-8')
>>> s3
'\xe4\xb8\xad\xe6\x96\x87'
>>> type(s3)
<type 'str'>
>>> type(b'hello')
<type 'str'>

Python3 与 Python2 的区别

python3 中的 str 在python2中叫 unicode, bytes 对象对应 python2 中的 str 对象。python2中str对象有一个 encode 方法,文本字符对象(unicode)有一个decode方法。

unicode.decode()
>>> a = u'中文'
>>> a.decode('utf-8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/encodings/utf_8.py", line 16, in decode
    return codecs.utf_8_decode(input, errors, True)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)
>>> 

unicode.decode() 实际执行过程为unicode.encode('ascii').decode('utf-8')

str.encode()
>>> b = '中文'
>>> b.encode('utf-8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 0: ordinal not in range(128)
>>> 

str.encode() 实际执行过程为 str.decode('ascii').encode('utf-8')

可以通过设置默认编码来减少错误

import sys
reload(sys)

# 需要 reload sys 模块后才会有 setdefaultencoding 方法
sys.setdefaultencoding('utf-8')
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值