paragbaxi paragbaxi - 3 years ago 148
Python Question

Convert an excel or spreadsheet column letter to its number in Pythonic fashion

Is there a more pythonic way of converting excel-style columns to numbers (starting with 1)?

Working code up to two letters:

def column_to_number(c):
"""Return number corresponding to excel-style column."""
for l in c:
if not l in string.ascii_letters:
return False
return number

Code runs:

>>> column_to_number('2')
>>> column_to_number('A')
>>> column_to_number('AB')

Three letters not working.

>>> column_to_number('ABA')
>>> column_to_number('AAB')

Reference: question answered in C#

Answer Source

There is a way to make it more pythonic (works with three or more letters and uses less magic numbers):

def col2num(col):
    num = 0
    for c in col:
        if c in string.ascii_letters:
            num = num * 26 + (ord(c.upper()) - ord('A')) + 1
    return num

And as a one-liner using reduce (does not check input and is less readable so I don't recommend it):

col2num = lambda col: reduce(lambda x, y: x*26 + y, [ord(c.upper()) - ord('A') + 1 for c in col])
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download