Encode differences between idle python and python

Peter Otten __peter__ at web.de
Tue Oct 10 02:23:28 EDT 2006


pretoriano_2001 at hotmail.com wrote:

> >>> u=u'áéíóú'
> >>> u
> u'\xe1\xe9\xed\xf3\xfa'
> >>> print u
> áéíóú
> >>> a=u.encode('latin-1')
> >>> a
> '\xe1\xe9\xed\xf3\xfa'
> >>> print a
> ßÚݾ·

That means that Python is better at guessing the correct encoding than you
are. Here's how you can make it share its secrets:

>>> import sys
>>> sys.stdout.encoding
'UTF-8' # something else on your machine (cp850, maybe)

Then you can use that encoding to print:

>>> your_encoding = sys.stdout.encoding
>>> print u"áéíóú".encode(your_encoding)
áéíóú

On the other hand: why not always print the unicode string directly?

Peter



More information about the Python-list mailing list