Printing characters outside of the ASCII range

Ian Kelly ian.g.kelly at gmail.com
Fri Nov 9 17:10:39 EST 2012


On Fri, Nov 9, 2012 at 2:46 PM, danielk <danielkleinad at gmail.com> wrote:
> D:\home\python>pytest.py
> Traceback (most recent call last):
>   File "D:\home\python\pytest.py", line 1, in <module>
>     print(chr(253).decode('latin1'))
> AttributeError: 'str' object has no attribute 'decode'
>
> Do I need to import something?

Ramit should have written "encode", not "decode".  But the above still
would not work, because chr(253) gives you the character at *Unicode*
code point 253, not the character with CP437 ordinal 253 that your
terminal can actually print.  The Unicode equivalents of those
characters are:

>>> list(map(ord, bytes([252, 253, 254]).decode('cp437')))
[8319, 178, 9632]

So these are what you would need to encode to CP437 for printing.

>>> print(chr(8319))
ⁿ
>>> print(chr(178))
²
>>> print(chr(9632))
■

That's probably not the way you want to go about printing them,
though, unless you mean to be inserting them manually.  Is the data
you get from your database a string, or a bytes object?  If the
former, just do:

print(data.encode('cp437'))

If the latter, then it should be printable as is, unless it is in some
other encoding than CP437.



More information about the Python-list mailing list