Skip to content

Instantly share code, notes, and snippets.

@robinhouston
Last active November 23, 2016 12:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robinhouston/99746cac543e6b3ea61f1d245e9b19cc to your computer and use it in GitHub Desktop.
Save robinhouston/99746cac543e6b3ea61f1d245e9b19cc to your computer and use it in GitHub Desktop.
Convert spreadsheet column letters (A,B, …, Z, AA, AB, …) to index numbers, and vice versa
def col_index(col):
"""Take a spreadsheet-style column specifier, e.g. A, M, ZZ,
and convert it to a one-based column index: A=1, Z=26, AA=27, etc.
"""
if not col or set(col) - set("ABCDEFGHIJKLMNOPQRSTUVWXYZ"):
raise Exception("Bad column specifier: '" + col + "'")
return reduce(lambda x,c: 26 * x + ord(c) - 64, col, 0)
def col_letters(index):
"""Take a one-based column index and convert it to a
spreadsheet-style column specifier: 1=A, 26=Z, 27=AA, etc.
"""
col_spec = ""
while index:
index, r = divmod(index - 1, 26)
col_spec = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"[r] + col_spec
return col_spec
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment