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)
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' '

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)))
abc

See Also

Documentation for the built-in functions chr, ord, and unichr in the Library Reference.

Get Python Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.