Highlight

2013-03-05

Digits to Excel column letters

A little tricky, so i'll note it here:

>>> def getLetters(n):
...     o = ""
...     while 1:
...             n, m = divmod(n-1, 26)
...             o = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"[m] + o
...             if n < 1: break
...     return o
...
>>> getLetters(1)
'A'
>>> getLetters(25)
'Y'
>>> getLetters(26)
'Z'
>>> getLetters(27)
'AA'

And i might as well include my old getCol function:

def getCol(s):
 z = 0
 for i in range(1, len(s) + 1):
  c = s[-i]
  z += ("ABCDEFGHIJKLMNOPQRSTUVWXYZ".find(c) + 1) * 26**(i - 1)
 return z