python chr()和ord()
通過help 查看相關(guān)函數(shù)的幫助文檔
>>>help (chr)
chr(...)
? ? chr(i) -> character ? ?
? ? Return a string of one character with ordinal i; 0 <= i < 256.
參數(shù)是0 - 256 的一個(gè)整數(shù),返回值是當(dāng)前整數(shù)對(duì)應(yīng)的ascii字符。參數(shù)可以是10進(jìn)制也可以是16進(jìn)制的形式
十六進(jìn)制:
>>> print chr(0x30), chr(0x31), chr(0x61)
0 1 a
>>> print chr(48), chr(49), chr(97)
0 1 a
unichr(...)
? ? unichr(i) -> Unicode character? ??
? ? Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.
unichr()和chr()函數(shù)功能基本一樣, 只不過是返回unicode的字符
ord(...)
? ? ord(c) -> integer
? ??Return the integer ordinal of a one-character string.
參數(shù)是一個(gè)ascii字符,返回值是對(duì)應(yīng)的十進(jìn)制整數(shù)
>>> 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()聯(lián)合起來使用,我們就可以對(duì)字符串進(jìn)行相關(guān)運(yùn)算的轉(zhuǎn)換
比如一個(gè)字符串str1,轉(zhuǎn)化成另一個(gè)字符串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