python中ASCII码和字符的转换方法

Python中使用内置函数 ord() 和 chr() 进行 ASCII 码和字符的转换。

ord() 函数用于将字符转换为它的 ASCII 码值,

其语法为:
ord(c)
其中,c 为要转换的字符。该函数将返回该字符对应的 ASCII 码值。

举个例子,下面的代码将字符 ‘A’ 转换为其对应的 ASCII 码值:
c = ‘A’
ascii_value = ord(c)
print(“The ASCII value of”, c, “is”, ascii_value)
输出结果为:
The ASCII value of A is 65


chr() 函数用于将 ASCII 码值转换为对应的字符,

其语法为:
chr(i)
其中,i 为要转换的 ASCII 码值。该函数将返回该 ASCII 码值对应的字符。

举个例子,下面的代码将 ASCII 码值 65 转换为其对应的字符:
ascii_value = 65
c = chr(ascii_value)
print(“The character with ASCII value”, ascii_value, “is”, c)
输出结果为:
The character with ASCII value 65 is A

如何将字符和 ASCII 码值进行转换完整实现代码

# Convert a character to its ASCII value
c = ‘A’
ascii_value = ord(c)
print(“The ASCII value of”, c, “is”, ascii_value)

# Convert an ASCII value to its character
ascii_value = 65
c = chr(ascii_value)
print(“The character with ASCII value”, ascii_value, “is”, c)

输出结果为:

The ASCII value of A is 65
The character with ASCII value 65 is A

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
xiaoxingxing的头像xiaoxingxing管理团队
上一篇 2023年5月28日
下一篇 2023年5月28日

相关推荐