Python:.encode('ascii', 'ignore') 做什么?

See*_*pha 3 python unicode

我是 Python 新手,正在查看工作中的一些代码。

我注意到有很多行包含row[0].encode('ascii', 'ignore').

我做了一些阅读,看起来它正在从 unicode 转换为字节。

这只是将字符串从 u'string' 转换为字符串的一种方法吗?

Joh*_*ooy 7

    编码(...)
        S.encode([编码[,错误]]) -> 对象

        使用注册用于编码的编解码器对 S 进行编码。编码默认值
        为默认编码。可能会给出错误来设置不同的错误
        处理方案。默认值为“严格”,这意味着会出现编码错误
        UnicodeEncodeError。其他可能的值是“忽略”、“替换”和
        'xmlcharrefreplace' 以及任何其他注册名称
        codecs.register_error 能够处理 UnicodeEncodeErrors。

因此它将 unicode 字符串编码为 ascii 并忽略错误

>>> "hello\xffworld".encode("ascii")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character '\xff' in position 5: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)

>>> "hello\xffworld".encode("ascii", "ignore")
b'helloworld'
Run Code Online (Sandbox Code Playgroud)