Python chr() 函式



Python 的chr()函式用於獲取特定Unicode值的字串表示。

簡單來說,如果您有一個表示字元Unicode程式碼點的數字,使用該數字呼叫chr()函式將得到實際的字元。例如,呼叫“chr(65)”得到'A',因為65代表大寫字母'A'的Unicode程式碼點。此函式是“ord()”函式的反函式,後者提供給定字元的程式碼點。

chr()函式接受0到1114111範圍內的Unicode值。如果提供的值超出此範圍,則函式會引發ValueError

語法

以下是python chr()函式的語法:

chr(num)

引數

此函式接受一個整數值作為引數。

返回值

此函式返回一個字串,表示具有給定ASCII碼的字元。

示例1

以下是python chr()函式的一個示例。在這裡,我們正在檢索對應於“83”的Unicode值的字串:

unicode_value = 83
string = chr(unicode_value)
print("The string representing the Unicode value 83 is:", string)

輸出

以下是上述程式碼的輸出:

The string representing the Unicode value 83 is: S

示例2

在這裡,我們使用chr()函式檢索Unicode值陣列的字串值:

unicode_array = [218, 111, 208]
for unicode in unicode_array:
   string_value = chr(unicode)
   print(f"The string representing the Unicode value {unicode} is:", string_value)

輸出

獲得的輸出如下:

The string representing the Unicode value 218 is: Ú
The string representing the Unicode value 111 is: o
The string representing the Unicode value 208 is: Ð

示例3

在此示例中,我們正在連線Unicode值“97”和“100”的字串值:

unicode_one = 97
unicode_two = 100
string_one = chr(unicode_one)
string_two = chr(unicode_two)
concatenated_string = string_one + string_two
print("The concatenated string from the Unicode values is:", concatenated_string)

輸出

產生的結果如下:

The concatenated string from the Unicode values is: ad

示例4

如果傳遞給chr()函式的Unicode值超過範圍,即大於1個字元長度的字串,則會引發ValueError。

在這裡,我們向chr()函式傳遞“-999”以演示值錯誤:

unicode_value = -999
string_value = chr(unicode_value)
print("The string representation for Unicode values -999 is:", string_value)

輸出

我們可以在輸出中看到,因為我們傳遞了一個長度大於1的無效Unicode值,所以我們得到了一個ValueError:

Traceback (most recent call last):
  File "C:\Users\Lenovo\Desktop\untitled.py", line 2, in <module>
    string_value = chr(unicode_value)
ValueError: chr() arg not in range(0x110000)
python_type_casting.htm
廣告