python - 为什么我在 Python 2.4 中使用 Unicode 数据时会出现 ASCII 编码错误,而在 2.7 中却不会?

标签 python exception unicode encoding

我有一个程序,当在 Python 2.7 中运行时,它会向标准输出生成正确的 Unicode 输出。在 Python 2.4 中运行时,我得到 UnicodeEncodeError: 'ascii' codec can't encode characters in position 1-4: ordinal not in range(128)。 2.4 版和 2.7 版之间有什么变化现在可以使用?

最佳答案

虽然我在其他地方找不到任何提及它的地方,但似乎 Python 2.7 会自动将文本转换为终端编码,而不是像预期的那样抛出错误。

Python 2.7:

> echo $LANG
en_US.UTF-8
> python -c 'import sys; print sys.getdefaultencoding()'
ascii

> python -c 'import sys; sys.stdout.write(u"\u03A3")'
Σ
> python -c 'import sys; sys.stdout.write(u"\u03A3".encode("utf8"))'
Σ

Python 2.6(在另一个盒子上)

> echo $LANG
en_US.UTF-8
> python -c 'import sys; print sys.getdefaultencoding()'
ascii

> python -c 'import sys;  sys.stdout.write(u"\u03A3")'
Traceback (most recent call last):
  File "<string>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec cant encode character u'\u03a3' in position 0: ordinal not in range(128)
> python -c 'import sys;  sys.stdout.write(u"\u03A3".encode("utf8"))'
Σ

无论如何,在输出前对数据进行 .encode("utf8") 应该可以避免这个问题。

关于python - 为什么我在 Python 2.4 中使用 Unicode 数据时会出现 ASCII 编码错误,而在 2.7 中却不会?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7182384/

相关文章:

python - numpy "TypeError: ufunc ' bitwise_and' 不支持输入类型”并且输入无法安全地强制为任何支持的类型

python - 用于 Python 的 RPC 库

delphi - 是否可以有一个全局异常钩子(Hook)?

java - 对于字符类型,方法 isDefined(char) 未定义

python - Python 是否禁止使用两个相似的 Unicode 标识符?

python - 如何使用pathlib来显示两种模式?

c# - 输入字符串的格式不正确

c# - 无法通过链接服务器访问数据库

c - ANSI C : isprint() returns true for non-ASCII character?

python - Keras 中的特征提取