欢迎访问宙启技术站
智能推送

如何使用Python的chr和ord函数来实现字符与ASCII码之间的转换?

发布时间:2023-11-10 11:34:04

在Python中,chr()函数用于将一个ASCII码转换为对应的字符,ord()函数用于将一个字符转换为对应的ASCII码。

下面是使用chr()和ord()函数实现字符与ASCII码之间转换的几个示例:

示例1:将字符转换为ASCII码

char = 'A'
ascii_code = ord(char)
print(f"The ASCII code of '{char}' is: {ascii_code}")

输出:

The ASCII code of 'A' is: 65

示例2:将ASCII码转换为字符

ascii_code = 65
char = chr(ascii_code)
print(f"The character of ASCII code {ascii_code} is: '{char}'")

输出:

The character of ASCII code 65 is: 'A'

示例3:将字符串转换为对应的ASCII码列表

string = "Hello"
ascii_codes = [ord(char) for char in string]
print(f"The ASCII codes of '{string}' are: {ascii_codes}")

输出:

The ASCII codes of 'Hello' are: [72, 101, 108, 108, 111]

示例4:将ASCII码列表转换为对应的字符串

ascii_codes = [72, 101, 108, 108, 111]
string = ''.join(chr(code) for code in ascii_codes)
print(f"The string of ASCII codes {ascii_codes} is: '{string}'")

输出:

The string of ASCII codes [72, 101, 108, 108, 111] is: 'Hello'

通过使用chr()和ord()函数,我们可以方便地进行字符和ASCII码之间的转换,从而在需要时进行编码和解码操作。