Python ord() 函数用于检索表示给定字符的 Unicode 码位的整数。Unicode 码位是 Unicode 标准中分配给每个字符的唯一编号,它们是从 0 到 0x10FFFF(十进制 1114111)的非负整数。
该函数可以接受长度为 1 的字符或字符串,从而允许参数同时接受单引号 ('') 和双引号 (“”)。因此,当您对字符使用 ord() 函数时,它会通知您在 Unicode 标准中表示该字符的特定数字。
例如,使用 ord('A') 将返回 65,因为 65 是大写字母 'A' 的 Unicode 码位。
语法
以下是 python ord() 函数的语法 -
ord(ch)
参数
此函数接受单个字符作为其参数。
返回值
此函数返回一个整数,该整数表示给定字符的 Unicode 码位。
示例 1以下是 python ord() 函数的示例。在这里,我们检索字符 “S” 的 Unicode 值 -
character = 'S'
unicode_value = ord(character)
print("The Unicode value of character S is:", unicode_value)
输出
以下是上述代码的输出 -
The Unicode value of character S is: 83
示例 2
在这里,我们使用 ord() 函数检索特殊字符 “*” 的 Unicode 值 -
character = '*'
unicode_value = ord(character)
print("The Unicode value of character * is:", unicode_value)
输出
获得的输出如下 -
The Unicode value of character * is: 42
示例 3
在此示例中,我们采用两个字符 “S” 和 “A” 并查找它们各自的 Unicode 值,这些值是这些字符的数字表示形式。然后,我们将这些 Unicode 值相加以检索结果 -
character_one = "S"
character_two = "A"
unicode_value_one = ord(character_one)
unicode_value_two = ord(character_two)
unicode_addition = unicode_value_one + unicode_value_two
print("The added Unicode value of characters S and A is:", unicode_addition)
输出
生成的结果如下 -
The added Unicode value of characters S and A is: 148
示例 4
如果我们将长度大于 2 的字符串传递给 ord() 函数,它将引发 TypeError。
在这里,我们将 “SA” 传递给 ord() 函数来演示类型错误 -
string = "SA"
unicode_value = ord(string)
print("The added Unicode value of string SA is:", unicode_value)
输出
我们可以在输出中看到我们得到一个 TypeError,因为我们传递了一个长度大于 1 的字符串 -
Traceback (most recent call last):
File "C:\Users\Lenovo\Desktop\untitled.py", line 3, in <module>
unicode_value = ord(string)
TypeError: ord() expected a character, but string of length 2 found
File "C:\Users\Lenovo\Desktop\untitled.py", line 3, in <module>
unicode_value = ord(string)
TypeError: ord() expected a character, but string of length 2 found