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

前端 未结 17 1224
夕颜
夕颜 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 04:47

    Here's what I use (wrote before I found this page):

    def col_to_index(col):
        return sum((ord(c) - 64) * 26**i for i, c in enumerate(reversed(col))) - 1
    

    And some runs:

    >>> col_to_index('A')
    1
    >>> col_to_index('AB')
    28
    >>> col_to_index('ABCD')
    19010
    

提交回复
热议问题