chr(i) ASCII under Python 3

Dave Angel davea at ieee.org
Tue Apr 27 05:26:35 EDT 2010


Dodo wrote:
> Hi all,
> Under python 2.6, chr() "Return a string of one character whose ASCII 
> code is the integer i." (quoted from docs.python.org)
> Under python 3.1, chr() "Return the string of one character whose 
> Unicode codepoint is the integer i."
>
> I want to convert a ASCII code back to a character under python 3, not 
> Unicode.
>
> How can I do that?
>
> Dorian
>
Like a lot of things, it depends on why you're asking what you are.

Characters are in Unicode on Python 3.x, by definition.  That's not a 
problem, it's a feature.  Such a character is 16 bits, and if it's an 
ASCII value, the bottom 7 bits exactly match ASCII, and the remaining 
ones are zero.

However, sometimes you don't really want strings of characters, you want 
an "array of 8 bit values," and you're used to the equivalence that 
earlier versions of Python give you.  In those cases, sometimes a string 
(Unicode) works transparently, and sometimes you really want a byte 
array.  Simplest example is when you're calling a DLL written in another 
language.

The types bytes and bytearray are considered sequences of integers (each 
of range 0 to 255), rather than characters.  And there are ways to 
convert back and forth between those and real strings.

DaveA






More information about the Python-list mailing list