杰瑞科技汇

Python中ASCII字符如何转为int?

在 Python 中,将 ASCII 字符转换为对应的整数值(即 ASCII 码)可以使用内置函数 ord(),以下是详细说明和示例:


使用 ord() 函数

ord(c) 返回单个字符 c 的 Unicode 编码值(对于 ASCII 字符,即 ASCII 码)。

示例代码

char = 'A'
ascii_value = ord(char)
print(f"ASCII value of '{char}' is: {ascii_value}")  # 输出: 65
char = 'a'
print(f"ASCII value of '{char}' is: {ord(char)}")  # 输出: 97
char = '0'
print(f"ASCII value of '{char}' is: {ord(char)}")  # 输出: 48

处理字符串(多个字符)

如果输入是一个字符串,可以通过遍历每个字符来获取对应的 ASCII 码:

示例代码

text = "Hello"
for char in text:
    print(f"ASCII of '{char}': {ord(char)}")

输出:

ASCII of 'H': 72
ASCII of 'e': 101
ASCII of 'l': 108
ASCII of 'l': 108
ASCII of 'o': 111

反向转换:int 转 ASCII

如果需要将整数(ASCII 码)转换回字符,使用 chr() 函数:

示例代码

ascii_code = 65
char = chr(ascii_code)
print(f"Character for ASCII {ascii_code} is: '{char}'")  # 输出: 'A'

注意事项

  • ord() 仅接受单个字符,否则会抛出 TypeError
    ord("AB")  # 报错: TypeError: ord() expected a character, but string of length 2 found
  • ASCII 码范围是 0-127,但 ord() 也支持扩展字符(如 Unicode 字符)。

实际应用场景

  • 加密/解密:通过字符的 ASCII 码进行简单加密。
  • 数据校验:检查字符是否为数字或字母。
  • 协议通信:将字符转换为二进制数据传输。

需求 函数 示例
字符 → ASCII 码 ord() ord('A')65
ASCII 码 → 字符 chr() chr(65)'A'
字符串逐字符转换 循环 [ord(c) for c in "ABC"][65, 66, 67]

通过 ord()chr(),可以轻松实现字符与整数值之间的转换。

分享:
扫描分享到社交APP
上一篇
下一篇