gpt4 book ai didi

python - 使用默认编码设置为 ASCII 的打印时没有 UnicodeError

转载 作者:太空狗 更新时间:2023-10-30 00:46:37 26 4
gpt4 key购买 nike

看完后:Dive into Python: Unicode Discussion

我很想尝试在 indic script 中打印我的名字。我正在使用 v2.7.2 -

>>> import sys
>>> sys.getdefaultencoding()
'ascii'
>>> name = u'\u0935\u0948\u092D\u0935'
>>> print name
वैभव

我期待 print name 给我 UnicodeError 因为 defaultencoding 设置为 ASCII 所以自动- 从 Unicode 强制转换为 ASCII 不应该工作。

我错过了什么?

最佳答案

print uses sys.stdout.encoding , 而不是 sys.getdefaultencoding():

When Python finds its output attached to a terminal, it sets the sys.stdout.encoding attribute to the terminal's encoding. The print statement's handler will automatically encode unicode arguments into str output.

>>> import sys
>>> print(sys.stdout.encoding)
utf-8
>>> print(sys.getdefaultencoding())
ascii
>>> name = u'\u0935\u0948\u092D\u0935'
>>> print name
वैभव

关于python - 使用默认编码设置为 ASCII 的打印时没有 UnicodeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6876877/

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