Python中chr、unichr、ord字符函数之间的对比

一. python3中的chr()

Python2中使用的chr()将Ascii的值转换成对应字符,unichr()将Unicode的值转换成对应字符
我们发现Python3中该内置函数消失了,实际上是Python3中的chr()不仅仅支持Ascii的转换,直接支持了更为适用的Unicode转换。

#输入Unicode编码起始值和终止值,打印此范围内所有字符
beg = int(input("请输入起始值:"))
end = int(input("请输入终止值:"))
print("十进制编码\t十六进制编码\t字符")
for i in range(beg,end+1):
    print("{}\t\t\t{}\t\t\t{}".format(i,hex(i),chr(i))) #hex()转十六进制 chr()求十进制或十六进制对应的字符

    1
    2
    3
    4
    5
    6

9472-9599为全部制表符可以测试一下

Unicode字符编码表:https://blog.csdn.net/zhenyu5211314/article/details/51537778
---------------------  
作者:XerCis  
来源:CSDN  
原文:https://blog.csdn.net/lly1122334/article/details/80598983  
版权声明:本文为博主原创文章,转载请附上博文链接!

二. chr、unichr、ord字符函数之间的对比

  • ord是unicode ordinal的缩写,即编号
  • chr是character的缩写,即字符
  • ord和chr是互相对应转换的.
  • 但是由于chr局限于ascii,长度只有256,于是又多了个unichr.

?

1

2

3

4

5

6

7

8

9

10

>>c = u'康'

>>c

u'\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的异常。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

>>> 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

猜你喜欢

转载自blog.csdn.net/SeaSky_Steven/article/details/86678225