3.17 Converting Between Characters and Values


Credit: Luther Blissett

3.17.1 Problem

You need to turn a character into its numeric ASCII (ISO) or Unicode code, and vice versa.

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

3.17.3 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

3.17.4 See Also

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



Python Cookbook
Python Cookbook
ISBN: 0596007973
EAN: 2147483647
Year: 2005
Pages: 346

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net