在字符和数字间相互转换
Problem
You need to turn a character into its numeric ASCII (ISO) or Unicode code, and vice versa.
将字符转换成ASCII码或者Unicode码

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 its argument a Unicode string of length one, in which case it returns a Unicode code value, up to 65536. To make a Unicode string of length one from a numeric Unicode code value, use the built-in function unichr:

>>> print ord(u’\u2020′)
8224
>>> print repr(unichr(8224))
u’\u2020′


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 or Unicode code, and vice versa. The built-in functions ord, chr, and unichr cover all the related needs. Note, in particular, the huge difference between chr(n) and str(n), which beginners sometimes confuse…:

>>> print repr(chr(97))
‘a’
>>> print repr(str(97))
‘97′

请注意str和chr的区别:
chr用0-255的整形作为参数,返回相应的按照ASCII码对应出来的单字节字符串,str用任何整型作为参数,返回的则是该数字相应的字符串格式。
chr takes as its argument a small integer and returns the corresponding single-character string according to ASCII, while str, called with any integer, returns the string that is the decimal representation of that integer.

To turn a string into a list of character value codes, use the built-in functions map and ord together, as follows:

>>> print map(ord, ‘ciao’)
[99, 105, 97, 111]


To build a string from a list of character codes, use ”.join, map and chr; for example:

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


See Also
Documentation for the built-in functions chr, ord, and unichr in the Library Reference and Python in a Nutshell.


评论

该日志第一篇评论

发表评论

评论也有版权!