Python ord() and chr() are built-in functions. They are used to convert a character to an int and vice versa.
Python ord()和chr()是内置函数。 它们用于将字符转换为int,反之亦然。
Python ord() and chr() functions are exactly opposite of each other.
Python的ord()和chr()函数彼此完全相反。
Python ord() (Python ord())
Python ord() function takes string argument of a single Unicode character and return its integer Unicode code point value. Let’s look at some examples of using ord() function.
Python ord()函数采用单个Unicode字符的字符串参数,并返回其整数Unicode代码点值。 让我们看一些使用ord()函数的示例。
x = ord('A')
print(x)
print(ord('ć'))
print(ord('ç'))
print(ord('$'))
Output:
输出:
65
263
231
36
Python的chr() (Python chr())
Python chr() function takes integer argument and return the string representing a character at that code point.
Python chr()函数采用整数参数,并返回表示该代码点处字符的字符串 。
y = chr(65)
print(y)
print(chr(123))
print(chr(36))
Output:
输出:
A
{
$
ć
Since chr() function takes an integer argument and converts it to character, there is a valid range for the input.
由于chr()函数采用整数参数并将其转换为字符,因此输入存在有效范围。
The valid range for the argument is from 0 through 1,114,111 (0x10FFFF in hexadecimal format). ValueError will be raised if the input integer is outside that range.
参数的有效范围是从0到1,114,111(十六进制格式为0x10FFFF)。 如果输入整数超出该范围,将引发ValueError。
chr(-10)
Output:
输出:
ValueError: chr() arg not in range(0x110000)
Let’s see an example of using ord() and chr() function together to confirm that they are exactly opposite of another one.
让我们来看一个使用ord()和chr()函数来确认它们与另一个完全相反的示例。
print(chr(ord('ć')))
print(ord(chr(65)))
Output:
输出:
ć
65
That’s all for a quick introduction of python ord() and chr() functions.
这就是快速介绍python ord()和chr()函数的全部内容。
Reference: Official Documentation – ord, Official Documentation – chr