Convert spreadsheet number to column letter

前端 未结 13 1265
太阳男子
太阳男子 2020-11-30 05:47

I\'m looking for the opposite to this Q&A: Convert an excel or spreadsheet column letter to its number in Pythonic fashion.

or this one but in python How to conv

13条回答
  •  孤街浪徒
    2020-11-30 06:11

    Edited after some tough love from Meta

    The procedure for this involves dividing the number by 26 until you've reached a number less than 26, taking the remainder each time and adding 65, since 65 is where 'A' is in the ASCII table. Read up on ASCII if that doesn't make sense to you.

    Note that like the originally linked question, this is 1-based rather than zero-based, so A -> 1, B -> 2.

    def num_to_col_letters(num):
        letters = ''
        while num:
            mod = (num - 1) % 26
            letters += chr(mod + 65)
            num = (num - 1) // 26
        return ''.join(reversed(letters))
    

    Example output:

    for i in range(1, 53):
        print i, num_to_col_letters(i)
    1 A
    2 B
    3 C
    4 D
    ...
    25 Y
    26 Z
    27 AA
    28 AB
    29 AC
    ...
    47 AU
    48 AV
    49 AW
    50 AX
    51 AY
    52 AZ
    

提交回复
热议问题