Python 2和3针对字符串是不同的。对应关系以下:windows
Python 2.* | Python 3.* |
str | unicode |
bytes | str |
Python3我没有测试,下面主要谈谈Python2上的编码。测试
Python2中str表明字符串,unicode你懂得。Python内部主要是使用unicode,因此unicode属于内部使用,str是为了给人阅读。编码
示例(windows中文版环境):spa
>>> sys.version '2.7.8 (default, Jun 30 2014, 16:08:48) [MSC v.1500 64 bit (AMD64)]' >>> s='你好' >>> u=u'你好' >>> s '\xc4\xe3\xba\xc3' >>> u u'\u4f60\u597d' >>> print s 你好 >>> print u 你好 >>>
经常使用的两个方法:code
1 str的decode方法。ci
2 unicode的encode方法。unicode
因为Python内部语言级别使用unicode,因此一个unicode须要编码(encode)变为str,而反过来str是便于人阅读用的,是从unicode通过encode过来的,因此str的decode方法是变回unicode。字符串
例如:it
>>> s '\xc4\xe3\xba\xc3' >>> print s 你好 >>> u u'\u4f60\u597d' >>> print u 你好 >>> s.decode('gbk') u'\u4f60\u597d' >>> u.encode('gbk') '\xc4\xe3\xba\xc3' >>>
可是:str也有encode方法。而unicode也有decode方法。它们怎么使用呢?io
两种状况:
1 字符是英文等单字节字符,那么str的encode方法,与unicode(str)的encode的效果是同样的。即不变。而unicode的decode方法和str(unicode)的decode方法是同样的。
2 字符是多字节字符(例如中文,日语等)。那么str的encode方法和unicode的decode方法都会报错。
>>> s='hello' >>> s 'hello' >>> s.encode('gbk') 'hello' >>> unicode(s,'gbk').encode('gbk') 'hello' >>> s='你好' >>> s '\xc4\xe3\xba\xc3' >>> print s 你好 >>> s.encode('gbk') Traceback (most recent call last): File "<stdin>", line 1, in <module> UnicodeDecodeError: 'ascii' codec can't decode byte 0xc4 in position 0: ordinal not in range(128) >>> u=u'hello' >>> u u'hello' >>> u.decode('gbk') u'hello' >>> str(u).decode('gbk') u'hello' >>> u=u'你好' >>> u u'\u4f60\u597d' >>> print u 你好 >>> u.decode('gbk') Traceback (most recent call last): File "<stdin>", line 1, in <module> UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128) >>>
因此调用encode和decode方法时必须主要调用者是str仍是unicode。