Using ord() to convert letters to ints (Very basic)

jonquest89 picture jonquest89 · Jun 2, 2012 · Viewed 11.5k times · Source

Python beginner here. Trying to learn by reading code here and there. Came across this in a program designed to open Excel files in python. This function does a simple job--converts an Excel column letter label ('Z', or 'BB', or 'CCC') to an int using ord(). I was understanding just fine until I saw this portion of the conversion code:

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

What is the purpose of (1 + (ord(column[0]) - 65) versus just using (ord(column[0]) - 64) again. The "1 +" seems redundant. Does this have a purpose?

This is the full function:

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)

Answer

Emil Vikstr&#246;m picture Emil Vikström · Jun 2, 2012

No, it does not have a purpose. 1+x-65 = x-64 even in Python :-)

It may be that the original developer thought it was easier to understand what 65 means than 64. Both are magic numbers, though, and you are better off giving names to the the numbers by assigning them to variables.