如何在 Python 中将整数转换为字符?
pythonserver side programmingprogramming
要在 Python 中将整数转换为字符,我们可以使用 chr() 方法。chr() 是一个 Python 内置方法,它从整数返回一个字符。该方法接受一个整数值并返回与该整数相对应的 unicode 字符。
语法
char(number)
参数
该方法接受 0 到 1,114,111 范围内的单个整数。
返回值
相应整数参数的 unicode 字符。如果我们传递超出范围的值(即 range(0x110000)),它将引发 ValueError。此外,对于非整数参数,它还会引发 TypeError −。
示例
在此示例中,我们使用 chr() 方法将整数 100 转换为相应的 unicode 字符。这里,该方法返回给定整数的字符 d。
number = 100 # 将 chr() 函数应用于整数值 result = chr(number) print("整数 - {} 转换为字符 -".format(number), result)
输出
整数 - 100 转换为字符 - d
示例
从这个例子中我们可以看到 35 的 unicode 字符是 #,而 2000 的 unicode 字符是 ڐ。
number1 = 35 number2 = 2000 # 将 chr() 函数应用于整数值 print("整数 - {} 转换为字符-".format(number1), chr(number1)) print("整数 - {} 转换为字符 -".format(number2), chr(number2))
输出
整数 - 35 转换为字符 - # 整数 - 2000 转换为字符 - ڐ
示例
在此示例中,我们传递了一个超出范围的负整数,因此该方法返回 ValueError。
number = -100 # 对超出范围的值应用 chr() 函数 print(chr(number))
输出
Traceback (most recent call last): File "/home/cg/root/62945/main.py", line 4, in <module> print(chr(number)) ValueError: chr() arg not in range(0x110000)
示例
在这里,我们传递了一个超出范围的整数,因此该方法返回 ValueError。
number = 1114113 # 对超出范围的值应用 chr() 函数 print(chr(number))
输出
Traceback (most recent call last): File "/home/cg/root/69710/main.py", line 4, in <module> print(chr(number)) ValueError: chr() arg not in range(0x110000)
示例
在此示例中,我们已将非整数参数传递给 chr() 方法。因此,该方法返回 TypeError。
Parameter_ = 'abc' # 将 chr() 函数应用于非整数值 print(chr(Parameter_))
输出
Traceback (most recent call last): File "/home/cg/root/40075/main.py", line 4, inprint(chr(Parameter_)) TypeError: 'str' object cannot be interpreted as an integer