Is there a more pythonic way of converting excel-style columns to numbers (starting with 1)?
Working code up to two letters:
Use:
LETTERS = list(string.ascii_uppercase)
def column_number(column_id):
return sum([(LETTERS.index(j)+1)*(26**i) for i,j in enumerate(column_id[::-1])])
There are several parts to this one-liner, so here's the explanation:
column_id[::-1]
: reverses the string, e.g. converts 'AZ'
to 'ZA'
, there's a good reason to do so, which we will see in a bit.
enumerate()
: produces a iterable, e.g. (0, 'Z'), (1, 'A')
With some observation:
A -> 1 = (26**0)*1 # ** is the exponential operator
B -> 2 = (26**0)*2
Z -> 26 = (26**0)*26
AA -> 27 = (26**0)*1 + (26**1)*1
AB -> 28 = (26**0)*2 + (26**1)*1
AZ -> 52 = (26**0)*26 + (26**1)*1 # recall that we have (0, 'Z'), (1, 'A')
Reversing the column_id
and enumerate()
allows us to use the index as the exponent for 26. The rest is now trivial.
LETTERS.index(j)
: gives us the index of the letter in LETTERS
sum()
: takes a list of numbers and returns the total.