What are the uses of ord and chr in Python?

In Python, the ord() function is used to return the Unicode code of a character, while the chr() function is used to return the character of a given Unicode code.

The syntax of the ord() function is ord(c), where c is the character for which you want to obtain the Unicode code. It returns an integer representing the Unicode code for the given character. For example, ord(‘A’) returns 65 and ord(‘a’) returns 97.

The syntax of the chr() function is: chr(i), where i is a Unicode code. It returns a character whose Unicode code corresponds to the given integer. For example, chr(65) returns ‘A’, and chr(97) returns ‘a’.

Below are some examples of using the ord() and chr() functions:

print(ord('A'))  # 输出65
print(ord('a'))  # 输出97

print(chr(65))  # 输出'A'
print(chr(97))  # 输出'a'

# 可以与循环结合使用,打印出'A'到'Z'的字符和对应的Unicode码
for i in range(ord('A'), ord('Z')+1):
    print(chr(i), ord(chr(i)))

The above demonstrates the basic usage of the ord() and chr() functions, which are very useful for converting between characters and Unicode codes.

bannerAds