我是一名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)