Last active
November 23, 2016 12:33
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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