python chr()和ord()函数

来源:互联网 发布:阿里云销售好做吗 编辑:程序博客网 时间:2024/05/21 11:08

Python 2.7

交互式解释器下查询各函数的属性

>>> <span style="font-size: 13px; line-height: 24.05px; font-family: 'Microsoft YaHei', 微软雅黑, Arial, 'Lucida Grande', Tahoma, sans-serif; background-color: transparent;">help(chr)</span>
Help on built-in function chr in module __builtin__:

chr(...)
    chr(i) -> character
    
    Return a string of one character with ordinal i; 0 <= i < 256.

输入参数是0 - 256 (不包括256)的一个整数,返回值是当前整数对应的ascii字符。参数可以是10进制也可以是16进制的形式

十六进制:

>>> print chr(0x30), chr(0x31), chr(0x61)0 1 a

十进制:

>>> print chr(48), chr(49), chr(97)0 1 a

>>><span style="font-size: 13px; text-indent: 0em; line-height: 24.05px; font-family: 'Microsoft YaHei', 微软雅黑, Arial, 'Lucida Grande', Tahoma, sans-serif; background-color: transparent;">help(ord)</span>
Help on built-in function ord in module __builtin__:
ord(...)
    ord(c) -> integer
    
    Return the integer ordinal of a one-character string.

参数是一个ascii字符,返回值是对应的十进制整数


>>> print ord('a'), ord('0'), ord('1')97 48 49
>>> print "%x %x %x" % (ord('a'), ord('0'), ord('1'))61 30 31>>> print "%#x %#x %#x" % (ord('a'), ord('0'), ord('1'))0x61 0x30 0x31

通过chr()和ord()联合起来使用,我们就可以对字符串进行相关运算的转换

比如一个字符串str1,转化成另一个字符串str2, 使得 str2[i] = str1[i] - i

str1 = "eb;3ej8h">>> for i in range(0, len(str1)):...     print chr((ord(str1[i])-i)),... e a 9 0 a e 2 a
0 0