使用默认编码设置为ASCII的打印时没有Unicode错误

2024-04-26 21:28:06 发布

您现在位置:Python中文网/ 问答频道 /正文

读后: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,所以从UnicodeASCII的自动强制应该不起作用。你知道吗

我错过了什么?你知道吗


Tags: nameimportsysasciiunicodescript名字print
1条回答
网友
1楼 · 发布于 2024-04-26 21:28:06

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
वैभव

相关问题 更多 >