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。