Python ord()是什么?
本章介绍了python中的ord()函数的含义与作用,一般来说,ord()函数主要用来返回对应字符的ascii码,chr()主要用来表示ascii码对应的字符他的输入时数字,可以用十进制,也可以用十六进制。也就是说ord()函数是chr()函数(对于8位的ascii字符串)或unichr()函数(对于unicode对象)的配对函数,它以一个字符(长度为1的字符串)作为参数,返回对应的ascii数值,或者unicode数值,如果所给的unicode字符超出了你的python定义范围,则会引发一个typeerror的异常。
1 >>> ord("a")2 973 >>> chr(97)4 'a'
比如生成一个字母表list,我们就可以这样:
>>> [chr(i) for i in range(97,123)]['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p','q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
# 用户输入字符c = input("请输入一个字符: ") # 用户输入ASCII码,并将输入的数字转为整型a = int(input("请输入一个ASCII码: "))print( c + " 的ASCII 码为", ord(c))print( a , " 对应的字符为", chr(a))
1 请输入一个字符: a2 请输入一个ASCII码: 1013 a 的ASCII 码为 974 101 对应的字符为 e
或者这样:
>>> chr(65)'A'>>> ord('a')97>>> unichr(12345)u'u3039'>>> chr(12345)Traceback (most recent call last): File "<stdin>", line 1, in ? chr(12345)ValueError: chr() arg not in range(256)>>> ord(u'ufffff')Traceback (most recent call last): File "<stdin>", line 1, in ? ord(u'ufffff')TypeError: ord() expected a character, but string of length 2 found>>> ord(u'u2345')9029</stdin></stdin>