python中字符的ascii值


如何将字符的 ASCII 值作为 Python

此处

function ord() would get the int value of the char. And in case you want to
convert back after playing with the number, function chr() does the trick.

ord(‘a’)
97
chr(97)
‘a’
chr(ord(‘a’) + 3)
‘d’

在Python 2中,还有unichr函数,它返回[ Unicode < / a>字符,其序号是unichr参数:

>>> unichr(97)
u'a'
>>> unichr(1234)
u'u04d2'

在Python 3中,您可以使用chr来代替unichr

注意ord()本身并不给你ASCII值;它给你的字符的数字值是任何编码的。因此,如果你正在使用Latin-1,那么ord(’ä’)的结果可能是228,或者如果你使用的是UTF,它可能会引发TypeError
-8。它甚至可以返回Unicode代码点,而不是传递给Unicode:

>>> ord(u'a‚')
12354

未经作者同意,本文严禁转载,违者必究!