Parameter Details
encoding 要使用的编码方式,例如'ascii'、'utf8'等。
errors 错误处理模式,例如'replace'会用问号替换错误的字符,'ignore'会忽略错误的字符等。

Section 153.1: 编码/解码错误处理

.encode和.decode方法都有错误处理模式。

默认模式是'strict',在发生错误时会抛出异常。其他模式则更加宽容。

编码

>>> "Åí13.55".encode('ascii', errors='replace')
b'?13.55'
>>> "Åí13.55".encode('ascii', errors='ignore')
b'13.55'
>>> "Åí13.55".encode('ascii', errors='namereplace')
b'\\N{POUND SIGN}13.55'
>>> "Åí13.55".encode('ascii', errors='xmlcharrefreplace')
b'£13.55'
>>> "Åí13.55".encode('ascii', errors='backslashreplace')
b'\\xa313.55'

编码/解码错误处理

解码

>>> b = "Åí13.55".encode('utf8')
>>> b.decode('ascii', errors='replace')
'..13.55'
>>> b.decode('ascii', errors='ignore')
'13.55'
>>> b.decode('ascii', errors='backslashreplace')
'\\xc2\\xa313.55'

编码/解码错误处理

总结

从上述内容可以看出,在处理Unicode和字节时,保持编码的一致性至关重要。

Section 153.2: 文件 I/O

以非二进制模式(例如'r'或'w')打开的文件处理字符串。默认编码是'utf8'。

open(fn, mode='r') # 以utf8编码打开文件进行读取
open(fn, mode='r', encoding='utf16') # 以utf16编码打开文件进行读取

# 错误:当期望字符串时,不能写入字节:
open("foo.txt", "w").write(b"foo")

以二进制模式(例如'rb'或'wb')打开的文件处理字节。由于没有编码,因此不能指定编码参数。

open(fn, mode='wb') # 打开文件以写入字节

# 错误:当期望字节时,不能写入字符串:
open(fn, mode='wb').write("hi")

Section 153.3: 基础

在Python 3中,str是Unicode字符串的类型,而bytes是原始字节序列的类型。

type("f") == type(u"f") # True, <class 'str'>
type(b"f") # <class 'bytes'>

基础

Unicode转字节

Unicode字符串可以通过.encode(encoding)转换为字节。

>>> "Åí13.55".encode('utf8')
b'\xc2\xa313.55'

>>> "Åí13.55".encode('utf16')
b'\xff\xfe\xa3\x001\x003\x00.\x005\x005\x00'

如果编码无法处理字符串,将抛出UnicodeEncodeError:

>>> "Åí13.55".encode('ascii')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character '\xa3' in position 0: ordinal not in range(128)

基础

字节转Unicode

字节可以通过.decode(encoding)转换为Unicode字符串。

只有通过适当的编码,字节序列才能转换为Unicode字符串!

>>> b'\xc2\xa313.55'.decode('utf8')
'Åí13.55'

如果编码无法处理字符串,将抛出UnicodeDecodeError:

>>> b'\xc2\xa313.55'.decode('utf16')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/csaftoiu/csaftoiu-github/yahoo-groupsbackup/.virtualenv/bin/../lib/python3.5/encodings/utf_16.py", line 16, in decode
  return codecs.utf_16_decode(input, errors, True)
UnicodeDecodeError: 'utf-16-le' codec can't decode byte 0x35 in position 6: truncated data

基础