0

当我运行这个 Python 2.7 代码时(编辑:更新了代码

import io
x = io.StringIO(u'\ud801')

CPython 运行良好,但 IronPython 抛出以下错误:

UnicodeEncodeError:
Unable to translate Unicode character \uD801 at index 0 to specified code page.

我认为这是因为U+D801 是一个不成对的代理,因此是一个无效字符,但是哪个实现在这里显示正确的行为?这段代码应该抛出还是不抛出?

4

1 回答 1

0

他们都是正确的,但没有做同样的事情。IronPython 似乎正在尝试print使用 Unicode 字符,但无法将其转换为当前代码页。如果你打印字符,你会得到与 Python 2.7 相同的行为:

>>> import io
>>> io.StringIO(u'\ud801').getvalue()
u'\ud801'
>>> print(io.StringIO(u'\ud801').getvalue())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\encodings\cp437.py", line 12, in encode
    return codecs.charmap_encode(input,errors,encoding_map)
UnicodeEncodeError: 'charmap' codec can't encode character u'\ud801' in position 0: character maps to <undefined>
于 2019-04-04T05:24:31.337 回答