python - 使用 ord() 将字母转换为整数(非常基本)

标签 python excel ord

这里是 Python 初学者。尝试通过在这里和那里阅读代码来学习。在一个旨在用 python 打开 Excel 文件的程序中遇到了这个问题。此函数执行一项简单的工作——使用 ord() 将 Excel 列字母标签(“Z”、“BB”或“CCC”)转换为 int。在看到这部分转换代码之前,我的理解还不错:

if clen == 1:
    return ord(column[0]) - 64
elif clen == 2:
    return ((1 + (ord(column[0]) - 65)) * 26) + (ord(column[1]) - 64)

(1 + (ord(column[0]) - 65) 与仅使用 (ord(column[0]) - 64) 的目的是什么再次。“1 +”似乎是多余的。这有目的吗?

这是完整的功能:

def column_index_from_string(column, fast=False):
    """Convert a column letter into a column number (e.g. B -> 2)"""

    column = column.upper()

    clen = len(column)

    if not fast and not all('A' <= char <= 'Z' for char in column):
        msg = 'Column string must contain only characters A-Z: got %s' % column
        raise ColumnStringIndexException(msg)

    if clen == 1:
        return ord(column[0]) - 64
    elif clen == 2:
        return ((1 + (ord(column[0]) - 65)) * 26) + (ord(column[1]) - 64)
    elif clen == 3:
        return ((1 + (ord(column[0]) - 65)) * 676) + ((1 + (ord(column[1]) - 65)) * 26) + (ord(column[2]) - 64)

最佳答案

不,它没有目的。 1+x-65 = x-64 即使在 Python 中也是如此:-)

最初的开发者可能认为 65 比 64 更容易理解。不过,两者都是神奇的数字,您最好通过将它们分配给变量来为这些数字命名。

关于python - 使用 ord() 将字母转换为整数(非常基本),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10865152/

相关文章:

mysql - 如何将excel文件导入MySQL数据库

python - 检查字符串是否包含希伯来字符的正确方法

python - miro如何嵌入vlc

python - 格式化 float 列表

python - 实现自定义 Python 身份验证处理程序

python - 如何在 Python 中获取 ASCII 西里尔字符代码?

python - 尝试 pip numba JIT 编译器时出错

Excel - VBA 每月的第一个工作日

vba - 复制数组中的值和颜色索引