Python ord() 函式



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
python_type_casting.htm
廣告