I\'m looking for the opposite to this Q&A: Convert an excel or spreadsheet column letter to its number in Pythonic fashion.
or this one but in python How to conv
This simple Python function works for columns with 1 or 2 letters.
def let(num):
alphabeth = string.uppercase
na = len(alphabeth)
if num <= len(alphabeth):
letters = alphabeth[num-1]
else:
letters = alphabeth[ ((num-1) / na) - 1 ] + alphabeth[((num-1) % na)]
return letters
def colnum_string(n):
string = ""
while n > 0:
n, remainder = divmod(n - 1, 26)
string = chr(65 + remainder) + string
return string
print(colnum_string(28))
#output:AB
Just to complicate everything a little bit I added caching, so the name of the same column will be calculated only once. The solution is based on a recipe by @Alex Benfica
import string
class ColumnName(dict):
def __init__(self):
super(ColumnName, self).__init__()
self.alphabet = string.uppercase
self.alphabet_size = len(self.alphabet)
def __missing__(self, column_number):
ret = self[column_number] = self.get_column_name(column_number)
return ret
def get_column_name(self, column_number):
if column_number <= self.alphabet_size:
return self.alphabet[column_number - 1]
else:
return self.alphabet[((column_number - 1) / self.alphabet_size) - 1] + self.alphabet[((column_number - 1) % self.alphabet_size)]
Usage example:
column = ColumnName()
for cn in range(1, 40):
print column[cn]
for cn in range(1, 50):
print column[cn]
Just for people still interest in this. The chosen answer by @Marius gives wrong outputs in some cases, as commented by @jspurim. Here is the my answer.
import string
def convertToTitle(num):
title = ''
alist = string.uppercase
while num:
mod = (num-1) % 26
num = int((num - mod) / 26)
title += alist[mod]
return title[::-1]
Recursive one line solution w/o libraries
def column(num, res = ''):
return column((num - 1) // 26, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[(num - 1) % 26] + res) if num > 0 else res
import math
num = 3500
row_number = str(math.ceil(num / 702))
letters = ''
num = num - 702 * math.floor(num / 702)
while num:
mod = (num - 1) % 26
letters += chr(mod + 65)
num = (num - 1) // 26
result = row_number + ("".join(reversed(letters)))
print(result)