gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 02:22:59 25 4
gpt4 key购买 nike

我有一个程序,当在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com