>>c = u'康'>>cu'/u5eb7'>>ord(c)24747>>chr(24247)ValueError: chr() arg not in range(256)>>unichr(24247)u'/u5eb7'
chr()函数用一个范围在range(256)内的(就是0~255)整数作参数,返回一个对应的字符。unichr()跟它一样,只不过返回的是Unicode字符,这个从Python 2.0才加入的unichr()的参数范围依赖于你的Python是如何被编译的。如果是配置为USC2的Unicode,那么它的允许范围就是range(65536)或0x0000-0xFFFF;如果配置为UCS4,那么这个值应该是range(1114112)或0x000000-0x110000。如果提供的参数不在允许的范围内,则会报一个ValueError的异常。
ord()函数是chr()函数(对于8位的ASCII字符串)或unichr()函数(对于Unicode对象)的配对函数,它以一个字符(长度为1的字符串)作为参数,返回对应的ASCII数值,或者Unicode数值,如果所给的Unicode字符超出了你的Python定义范围,则会引发一个TypeError的异常。
>>> 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
新闻热点
疑难解答
图片精选