Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

no UnicodeError when using print with a default encoding set to ASCII

Tags:

python

unicode

After reading: Dive into Python: Unicode Discussion

I got curious to try printing my name in the indic script. I am using v2.7.2 -

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

I was expecting print name to give me UnicodeError since the defaultencoding is set to ASCII so the auto-coercion to ASCII from Unicode shouldn't work.

What am I missing?

like image 909
Vaibhav Bajpai Avatar asked Jul 29 '11 17:07

Vaibhav Bajpai


1 Answers

print uses sys.stdout.encoding, not 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
वैभव
like image 156
unutbu Avatar answered Oct 21 '22 03:10

unutbu