Convert from numbers to letters

Jason Drew jasondrew72 at gmail.com
Fri May 20 09:47:25 EDT 2005


Er, yes! It's REALLY ugly! I was joking (though it works)! I retract it
from the code universe. (But patent pending nr. 4040404.)

Here's how I really would convert your (row_from_zero, col_from_zero)
tuple to spreadsheet "A1" coords, in very simple and easy to read code.

##def tuple2coord(tupl):
##    def colnr2digraph(colnr):
##        if colnr <= 26:
##            return chr(ord('A') + colnr-1)
##        m = colnr % 26
##        if m == 0:
##            m = 26
##        h = (colnr - m) / 26
##        return colnr2digraph(h) + colnr2digraph(m)
##
##    rowfromzero, colfromzero = tupl
##    row = rowfromzero+1
##    col = colfromzero+1
##    return colnr2digraph(col) + str(row)
##
##print tuple2coord((13,702))
### gives AAA14
### (because the tuple counts rows and columns from zero)

Note that this allows column nrs of any size, not just up to "ZZ". If
you really know the column limit is ZZ, then a lookup dictionary would
be a more efficient speed-wise solution. (Though I'd still use my nice
recursive no-brainer colnr2digraph function to populate the
dictionary.)

P.S. the line that says
h = (colnr - m) / 26
could really, in current Python, be just
h = colnr / 26
but the former is more language- and future-neutral.




More information about the Python-list mailing list