>>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定義范圍,則會引發(fā)一個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新聞熱點
疑難解答
圖片精選