wyc's domain

Excel Columns to List Indexes in Python

Posted on May 30, 2017
Tags: python

I was working on some CSV files for a project. I figured that it would be easier to refer to the columns by their Excel column letters (e.g., ‘A’, ‘B’, ‘AA’, ‘AZ’) than the column numbers.

Some clear benefits:

The snippet is here for anyone who would find it helpful.

def to_idx(letters):
    val = lambda i, x: (26**i) * (ord(x.lower()) - ord('a') + 1)
    return sum([val(i, x) for i, x in enumerate(letters[::-1])]) - 1

Here it is in action:

    >>> to_idx('A')
    >>> to_idx('AH')
    >>> to_idx('XFD')