Credit: Luther Blissett
That’s what the built-in functions
ord
and chr
are for:
>>> print ord('a') 97 >>> print chr(97) a
The built-in function ord
also accepts as an
argument a Unicode string of length one, in which case it returns a
Unicode code, up to 65536. To make a Unicode string of length one
from a numeric Unicode code, use the built-in function
unichr
:
>>> print ord(u'u2020') 8224 >>> print unichr(8224) u' '
It’s a mundane task, to be sure, but it is sometimes
useful to turn a character (which in Python just means a string of
length one) into its ASCII (ISO) or Unicode code, and vice versa. The
built-in functions ord
, chr
,
and unichr
cover all the related needs. Of course,
they’re quite suitable with the built-in function
map
:
>>> print map(ord, 'ciao')
[99, 105, 97, 111]
To build a string from a list of character codes, you must use both
map
and ''.join
:
>>> print ''.join(map(chr, range(97, 100)))
abc