文章来自《Python cookbook》.

翻译仅仅是为了个人学习,其它商业版权纠纷与此无关!

-- 0.706 [2004-09-27 16:13:02]

1. Converting Between Characters and Values 在字符与和编码值间转换

Credit: Luther Blissett

1.1. 问题 Problem

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

你的需要是,转换一个字符为它的ASCII(ISO)码 或Unicode码的数值, 以及作相反的转换。

1.2. 解决 Solution

That's what the built-in functions ord and chr are for:

那是内建函数 ord 和 chr 的目的:

>>> 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.

内建函数 ord 也可接受一个长度为一的Unicode字符串,在那种情况它返回一个Unicode码 , 直到65536 。

To make a Unicode string of length one from a numeric Unicode code, use the built-in function unichr:

为了要从一个Unicode码数值生成长度为一的Unicode字符串,使用内建函数 unichr:

>>> print ord(u'u2020')
8224
>>> print unichr(8224)
u' '

1.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:

将一个字符 ( 在 Python 中仅仅意谓着一个长度为一的字符串) 转换为它的ASCII(ISO)码 或Unicode码, 以及作相反的转换,是一件平凡的工作,的确,但是它有时是有用的。 内建函数 ord , chr 和 unichr 的功能覆盖了所有相关的需要。 当然,它们相当适合与内建函数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:

为了从一个字符代码列表来建立字符串,你得同时使用map和 ' '.join:

>>> print ''.join(map(chr, range(97, 100)))
abc

1.4. 参考 See Also

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