Unicode string output

Fredrik Lundh fredrik at effbot.org
Sun Jan 21 11:45:35 EST 2001


Alexander Kostyrkin wrote:
> Surprisingly printing a unicode string that contains a Japanese kanji
> character raises an exception
> For example
>
>     print u"\u55f4"
> UnicodeError: ASCII encoding error: ordinal not in range(128)
>
> Is there any way to overcome the problem?

If you don't specify what encoding to use on output, Python assumes
you're an encoding-ignorant american programmer <wink>, and defaults
to ASCII.

To use any other encoding, use the encode method:

    s = ...
    print s.encode("iso-latin-1")
    print s.encode("ascii", "ignore")

Also see the codecs modules:
http://www.python.org/doc/current/lib/module-codecs.html

Cheers /F





More information about the Python-list mailing list