Skip to main content
 首页 » 编程设计

python之如何像在 Python 2 中一样在 Python 3 中将 chr(0xdfff) 转换为 utf-8 字节

2025年01月19日34bhlsheji

下面的代码解释了我的问题。它在 Python 2.7 中按预期工作,但是,我尝试过的所有编码调用在 Python 3.5 中都失败了(请参阅下面的异常)...是否有人在设法避免此错误并使其在 Python 3.5 中正常工作在 Python 2.7 上?

import sys 
 
if sys.version_info[0] <= 2: 
    chr = unichr 
 
out = chr(0xdfff) 
print(repr(out)) # outputs '\udfff' both in Python 2 and 3 
assert out.encode('utf-8').decode('utf-8') == out 
assert out.encode('utf-8', errors='surrogateescape').decode('utf-8') == out 
assert out.encode('utf-8', errors='strict').decode('utf-8') == out 

Python 3.5 中的错误:

Traceback (most recent call last): 
  File "W:\rocky40\Projects\etk\coilib50\source\python\coilib50\io\xmlpickle\snippet.py", line 8, in <module> 
    assert out.encode('utf-8').decode('utf-8') == out 
UnicodeEncodeError: 'utf-8' codec can't encode character '\udfff' in position 0: surrogates not allowed 

请注意,不同的编码并不适合它,因为我在 Python 2 中以这种方式将文件写入磁盘,我需要能够将其加载回并再次转储到 Python 3 上,以便 Python 2 可以读取它再次(因此,实际写入的字节不应真正改变)。

请您参考如下方法:

经过更多搜索后,我注意到 https://docs.python.org/3/library/codecs.html#codec-base-classes指向特定于 utf-X 编解码器的 surrogatepass,因此,使用 surrogatepass 而不是 surrogateescape 似乎确实完成技巧并在 Python 3 上正常工作:

assert out.encode('utf-8', errors='surrogatepass' 
    ).decode('utf-8', errors='surrogatepass') == out