Python中的ord()函数

Python ord()函数 返回给定字符的Unicode代码。这个函数 接受一串 单位长度作为参数,并返回 Unicode 传递参数的等价性。换句话说,给定 对于长度为1的字符串,当参数为Unicode对象时,ord()函数返回一个整数,表示字符的Unicode代码点;当参数为8位字符串时,返回字节值。

null

Python ord()语法:

语法: 作战需求文件(ch)

Python ord()参数:

ch–一个unicode字符

Python ord()示例

例如,ord(’a’)返回整数97,ord(’€’)(欧元符号)返回8364。这是相反的 chr() 对于8位字符串和Unicode对象的unichr()。如果给定了Unicode参数,并且Python是使用UCS2 Unicode构建的,那么字符的代码点必须在[0..65535]范围内(包括[0..65535])。

注: 如果字符串长度超过一,则会引发TypeError。语法可以是ord(“a”)或ord(“a”),两者都会给出相同的结果。

例1: 集会示威 Python ord()函数的构造

python

# inbuilt function return an
# integer representing the Unicode code
value = ord ( "A" )
# writing in ' ' gives the same result
value1 = ord ( 'A' )
# prints the unicode value
print (value, value1)


输出:

65 65

示例2:Python ord()错误条件

A. 打字错误 当字符串长度不等于1时,将引发,如下所示:

Python3

# inbuilt function return an
# integer representing the Unicode code
# demonstrating exception
# Raises Exception
value1 = ord ( 'AB' )
# prints the unicode value
print (value1)


输出:

回溯(最近一次通话最后一次):

文件“/home/f988dfe667cdc9a8e5658464c87ccd18.py”,第6行,在

value1=ord(’AB’)

TypeError:ord()应为字符,但找到长度为2的字符串

Python ord()和chr()函数

方法返回一个字符串,该字符串表示Unicode代码点为整数的字符。

语法 :chr(num)

num:整数值

其中ord()方法对chr()函数的作用相反:

ord()和chr()函数示例

Python3

# inbuilt function return an
# integer representing the Unicode code
value = ord ( "A" )
# prints the unicode value
print (value)
# print the character
print ( chr (value))


输出:

65A
© 版权声明
THE END
喜欢就支持一下吧
点赞15 分享