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() 函数的示例。在这里,我们检索的是对应于 Unicode 值 “83” 的字符串 -
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: Ð
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
如果将超出范围的 Unicode 值(即大于 1 个字符的字符串长度)传递给 chr() 函数,则会引发 ValueError。
在这里,我们将 “-999” 传递给 chr() 函数以演示值 error -
unicode_value = -999
string_value = chr(unicode_value)
print("The string representation for Unicode values -999 is:", string_value)
输出
我们可以在输出中看到,我们得到了一个 ValueError,因为我们传递了一个长度大于 1 的无效 Unicode 值 -
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)
File "C:\Users\Lenovo\Desktop\untitled.py", line 2, in <module>
string_value = chr(unicode_value)
ValueError: chr() arg not in range(0x110000)