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

前端 未结 17 1227
夕颜
夕颜 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条回答
  •  Happy的楠姐
    2020-12-09 05:06

    Here is a recursive solution:

    def column_string_to_num(s):
        n = ord(s[-1]) - 64
        if s[:-1]:
            return 26 * (column_string_to_num(s[:-1])) + n
        else:
            return n
        
    column_string_to_num("AB")
    #output: 28
    

    The inverse can also be defined recursively, in a similar way:

    def column_num_to_string(n):
        n, rem = divmod(n - 1, 26)
        next_char = chr(65 + rem)
        if n:
            return column_string(n) + next_char
        else:
            return next_char
    
    column_num_to_string(28)
    #output: 'AB'
    

提交回复
热议问题