Python:unicode .encode,可以在不可编码的字符上调用函数吗?

ste*_*ssi 1 python unicode encoding

我有一个uncode的文本,我想用latin-1编码.某些字符无法编码.如果我使用带有"replace"参数的encode,我会得到问号标签字符,但是,有没有办法调用自定义函数来替换字符?

例如,我想将所有可能的字符转换为latin-1,并调用unidecode.unidecode()不可编码的字符.那可能吗?

R. *_*des 5

您可以使用创建自己的错误处理程序codecs.register_error('myerrorhandler', function).

>>> import codecs
>>> codecs.register_error('silly', lambda e: ('X', e.start+1))
>>> 'foöbar'.encode('ascii', 'silly')
b'foXbar'
>>>
Run Code Online (Sandbox Code Playgroud)