Converting Between Characters and Values
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')
97
>>> print chr(97)
aThe 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' '
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 (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)))
abcSee Also
Documentation for the built-in functions chr,
ord, and unichr in the
Library Reference.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access