Skip to Content
Python Cookbook
book

Python Cookbook

by Alex Martelli, David Ascher
July 2002
Intermediate to advanced
608 pages
15h 46m
English
O'Reilly Media, Inc.
Content preview from Python Cookbook

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.

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.
Start your free trial

You might also like

Modern Python Cookbook - Second Edition

Modern Python Cookbook - Second Edition

Steven F. Lott
Python Cookbook, 3rd Edition

Python Cookbook, 3rd Edition

David Beazley, Brian K. Jones

Publisher Resources

ISBN: 0596001673Supplemental ContentCatalog PageErrata