Python unichr() 函式



在 Python 2 中,unichr() 函式用於將 Unicode 程式碼點轉換為其對應的 Unicode 字元。它類似於 Python 3 中的 "chr()" 函式。

在 Python 2 中,字元預設使用 "unicode" 型別表示為 Unicode。unichr() 函式用於根據其相應的程式碼點建立 Unicode 字元。例如,呼叫 "unichr(65)" 將生成 Unicode 字元 'A',因為 65 對應於大寫字母 'A' 的 Unicode 程式碼點。

Python 2 中的 unichr() 函式在 Python 3 中已被棄用。相反,內建的 chr() 函式現在在 Python 3 中普遍用於 ASCII 和 Unicode 字元。

語法

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

unichr(num)

引數

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

返回值

此函式返回一個包含由該程式碼點表示的字元的 Unicode 字串。

示例 1

以下是 python unichr() 函式的示例。在這裡,我們從 Unicode 程式碼點 "65" 建立一個 Unicode 字元:

unicode_value = 65
string = unichr(unicode_value)
print("The string representing the Unicode value 65 is:", string)

輸出

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

('The string representing the Unicode value 65 is:', u'A')

示例 2

在這裡,我們線上程中使用 unichr() 函式來生成從 "65" 到 "69" 的程式碼點的 Unicode 字元:

for i in range(65, 70):
   unicode_char = unichr(i)
   print "The unicode string obtained is:", unicode_char

輸出

獲得的輸出如下:

The unicode string obtained is: A
The unicode string obtained is: B
The unicode string obtained is: C
The unicode string obtained is: D
The unicode string obtained is: E

示例 3

在此示例中,我們使用 unichr() 函式為程式碼點 "9786" 建立一個 Unicode 字元,該程式碼點對應於笑臉:

smiley_face = unichr(9786)
print smiley_face.encode('utf-8')

輸出

產生的結果如下:

😊

示例 4

以下示例顯示了 unichr() 函式的多功能性,它為 ASCII 程式碼點 "97" 和非 ASCII 程式碼點 "8364" 建立 Unicode 字元:

ascii_char = unichr(97)
non_ascii_char = unichr(8364)
print "The Unicode string obtained for ASCII is:", ascii_char
print "The Unicode string obtained for non-ASCII is:", non_ascii_char.encode('utf-8')

輸出

我們獲得如下所示的輸出:

The Unicode string obtained for ASCII is: a
The Unicode string obtained for non-ASCII is: €
python_type_casting.htm
廣告