ord函数用法:
ord()
函数是 Python 内置函数之一,它用于返回表示单个字符的 Unicode 码点(code point)。在 Python 中,字符是由 Unicode 码点表示的,每个字符都有一个唯一的 Unicode 码点。ord()
函数接受一个字符串参数(通常是一个字符),然后返回该字符的 Unicode 码点。
下面是 ord()
函数的基本用法示例
# 获取字符 'A' 的 Unicode 码点
print(ord('A')) # 输出:65
# 获取字符 '中' 的 Unicode 码点
print(ord('中')) # 输出:20013
需要注意的是,ord()
函数仅接受包含单个字符的字符串作为参数。如果传入多个字符或空字符串,将会引发 TypeError
异常
# 错误示例:传入多个字符
# TypeError: ord() expected a character, but string of length 2 found
print(ord('AB'))
# 错误示例:传入空字符串
# TypeError: ord() expected a character, but string of length 0 found
print(ord(''))
这就是 ord()
函数的基本用法。它在处理字符和字符编码时非常有用。