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
广告
© . All rights reserved.