_str__, 主如果用于展示,str(obj)或者print obj的时刻调用,返回值必定是一个str 对象
已知“严”的unicode是4E25(100111000100101),根据上表,可以发明4E25处在第三行典范围内(0000 0800-0000 FFFF),是以“严”的UTF-8编码须要三个字节,即格局是“1110xxxx 10xxxxxx 10xxxxxx”。然后,大年夜“严”的最后一个二进制位开端,依次大年夜后向前填入格局中的x,多出的位补0。如许就获得了,“严”的UTF-8编码是“11100100 10111000 10100101”,转换成十六进制就是E4B8A5。
__repr__, 是被repr(obj), 或者在终端直接打obj的时刻调用
- >>> us = u'严'
- >>> us
- u'\u4e25'
- >>> print us
- 严
可以看到,不应用print返回的是一个更能反竽暌钩对象本质的结不雅,即us是一个unicode对象(最前面的u表示,以及unicode编码是用的u),且“严”的unicode编码确切是4E25。而print调用可us.__str__,等价于print str(us),使得结不雅对用户更友爱。那么unicode.__str__是怎么转换成str的呢,谜底会在后面揭晓
unicode str utf-8关系
前面已经提到,unicode只是编码规范(只是字符与二进制的映射集合),而utf-8是具体的编码规矩(不仅包含字符与二进制的映射集合,并且映射后的二进制是可以用于存储和传输的),即utf-8负责把unicode转换成可存储和传输的二进制字符串即str类型,我们称这个转换过程为编码。而大年夜str类型到unicode类型的过程,我们称之为解码。
Python中应用decode()和encode()来进行解码和编码,以unicode类型作为中心类型。如下图所示
decode encode
str ---------> unicode --------->str
即str类型调用decode办法转换成unicode类型,unicode类型调用encode办法转换成str类型。for example
大年夜上可以看出encode与decode两个函数的感化,也可以看出’严’的utf8编码是E4B8A5。
就是说我们应用unicode.encode将unicode类型转换成了str类型,在膳绫擎也提到unicode.__str__也是将unicode类型转换成str类型。二者有什么却比呢
unicode.encode 与 unicode.__str__的差别
起首看看文档
- str.encode([encoding[, errors]])
- Return an encoded version of the string. Default encoding is the current default string encoding.
- object.__str__(self)
- Called by the str() built-in function and by the print statement to compute the “informal” string representation of an object.
留意:str.encode 这里的str是basestring,是str类型与unicode类型的基类
可以看到encode办法是有可选的参数:encoding 和 errors,在膳绫擎的例子中encoding即为utf-8;而__str__是没有参数的,我们可以猜想,对于unicode类型,__str__函数必定也是应用了某种encoding来对unicode进行编码。
起首不禁要问,如不雅encode办法没有带入参数,是什么样子的:
- >>> us.encode()
- Traceback (most recent call last):
- File "<stdin>", line 1, in <module>
- UnicodeEncodeError: 'ascii' codec can't encode character u'\u4e25' in position 0: ordinal not
推荐阅读
能拍照,还能视频通话?coolpad Dynobot儿童智能手表让你惊艳
市面上的绝大部分儿童手表都不能拍照,最大卖点的只是语音通话功能。Dynobot是市面上仅有的配备两个摄像头的儿童手表,支持480P视频通话。表盘30万像素满足孩子自拍需求,顶部200万像素摄像头可以拍孩子看到的任何画>>>详细阅读
本文标题:不想再被鄙视?那就看进来! 一文搞懂Python 2字符编码
地址:http://www.17bianji.com/lsqh/39888.html
1/2 1

网友点评
精彩导读
科技快报
品牌展示