在 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
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')
输出
生成的结果如下 -