Convert an excel or spreadsheet column letter to its number in Pythonic fashion

前端 未结 17 1272
夕颜
夕颜 2020-12-09 04:18

Is there a more pythonic way of converting excel-style columns to numbers (starting with 1)?

Working code up to two letters:



        
17条回答
  •  孤街浪徒
    2020-12-09 05:00

    I made this one-liner:

    colNameToNum = lambda cn: sum([((ord(cn[-1-pos]) - 64) * 26 ** pos) for pos in range(len(cn))])
    

    It works by iterating through the letters in reverse order and multiplying by 1, 26, 26 * 26 etc, then summing the list. This method would be compatible with longer strings of letters, too.

    I call it with:

    print(colNameToNum("AA")) # 27

    or

    print(colNameToNum("XFD")) # the highest column allowed, I believe. Result = 16384

提交回复
热议问题