Is there a more pythonic way of converting excel-style columns to numbers (starting with 1)?
Working code up to two letters:
Here is a recursive solution:
def column_string_to_num(s):
n = ord(s[-1]) - 64
if s[:-1]:
return 26 * (column_string_to_num(s[:-1])) + n
else:
return n
column_string_to_num("AB")
#output: 28
The inverse can also be defined recursively, in a similar way:
def column_num_to_string(n):
n, rem = divmod(n - 1, 26)
next_char = chr(65 + rem)
if n:
return column_string(n) + next_char
else:
return next_char
column_num_to_string(28)
#output: 'AB'