Python字符和字符值(ASCII或Unicode码值)转换方法

WBOY
Release: 2016-06-06 11:17:27
Original
1805 people have browsed it

目的

将一个字符转化为相应的ASCII或Unicode码,或相反的操作。

方法

对于ASCII码(0~255范围)

代码如下:


>>> print ord('A')
65
>>> print chr(65)
A


对于Unicode字符,注意仅接收长度为1的Unicode字符

代码如下:


>>> print ord(u'\u54c8')
21704
>>> print unichr(21704)

>>> print repr(unichr(21704))
u'\u54c8'

chr()和str()区别,一个仅接收0~255的数值返回对应于ASCII值的字符,一个接受任何类型返回字符串格式

代码如下:


>>> chr(97)
'a'
>>> str(97)
'97'

使用map和以上函数,来获得包含字符值或者码值的列表

代码如下:


>>> print map(ord,(u'\u54c8',u'\u54c9'))
[21704, 21705]

>>> print map(unichr,range(21704,21707))
[u'\u54c8', u'\u54c9', u'\u54ca']


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template