Recipe 1.2. Converting Between Characters and Numeric Codes
Credit: Luther Blissett
Problem
You need to turn a character into its
numeric ASCII (ISO) or Unicode code, and vice versa.
Solution
That's what the built-in functions
ord and chr are for:
>>> print ord('a')The built-in function ord also accepts as its
97
>>> print chr(97)
a
argument a Unicode string of length one, in which case it returns a
Unicode code value, up to 65536. To make a Unicode string of length
one from a numeric Unicode code value, use the built-in function
unichr:
>>> print ord(u'\u2020')
8224
>>> print repr(unichr(8224))
u'\u2020'
Discussion
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 or Unicode code, and vice versa. The
built-in functions ord, chr,
and unichr cover all the related needs. Note, in
particular, the huge difference between chr(n) and
str(n), which beginners sometimes confuse...:
>>> print repr(chr(97))chr takes as its argument a small integer and
'a'
>>> print repr(str(97))
'97'
returns the corresponding single-character string according to ASCII,
while str, called with any integer, returns the
string that is the decimal representation of that integer.To turn a string into a list of character value codes, use the
built-in functions map and ord
together, as follows:
>>> print map(ord, 'ciao')To build a string from a list of
[99, 105, 97, 111]
character codes, use ''.join,
map and chr; for example:
>>> print ''.join(map(chr, range(97, 100)))
abc
See Also
Documentation for the built-in functions chr,
ord, and unichr in the
Library Reference and Python in a
Nutshell.