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

前端 未结 17 1231
夕颜
夕颜 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:05

    Here is one way to do it. It is a variation on code in the XlsxWriter module:

    def col_to_num(col_str):
        """ Convert base26 column string to number. """
        expn = 0
        col_num = 0
        for char in reversed(col_str):
            col_num += (ord(char) - ord('A') + 1) * (26 ** expn)
            expn += 1
    
        return col_num
    
    
    >>> col_to_num('A')
    1
    >>> col_to_num('AB')
    28
    >>> col_to_num('ABA')
    729
    >>> col_to_num('AAB')
    704
    

提交回复
热议问题