📜  ord python3 - Python (1)

📅  最后修改于: 2023-12-03 15:18:10.319000             🧑  作者: Mango

主题:ord python3 - Python

介绍

ord 是一种内置函数,用于返回字符串中某个字符对应的 ASCII 值。在 Python 3 中,ord 函数可以与字符串一起使用,该函数将单个字符作为参数,并返回该字符的数字 ASCII 值。

ASCII(American Standard Code for Information Interchange,美国信息交换标准代码)是一种将字母、数字和其他字符编码为数字的标准。ASCII 码使用一个 7 位二进制数字表示每个字符,所以只能表示 128 个不同的字符。

用法

ord 函数可接收一个参数,即要返回 ASCII 值的字符。使用 ord 函数时,请将要转换为 ASCII 值的字符作为参数传递。函数将返回对应的 ASCII 值。

print(ord('a')) # 97

如果 ord 函数接收的参数不是长度为 1 的字符串,则会抛出 TypeError 异常。

print(ord('Python'))
# TypeError: ord() expected a character, but string of length 6 found
示例

以下是示例代码,演示如何使用 ord 函数计算字符串中字符的 ASCII 值。

# 计算字符串中第一个字符的 ASCII 值
print(ord('P')) # 80

# 计算字符串中最后一个字符的 ASCII 值
print(ord('n')) # 110

# 将字符串转换为 ASCII 码序列
s = 'Python3'
ascii_list = [ord(c) for c in s]
print(ascii_list) # [80, 121, 116, 104, 111, 110, 51]
结论

ord 函数是将字符转换为对应 ASCII 值的常用方法。如果您需要处理文本数据并计算其属性,请考虑使用 ord 函数。