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

Discussão em 'Python' iniciado por Stack, Março 8, 2025.

  1. Stack

    Stack Membro Participativo

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

    Working code up to two letters:

    def column_to_number(c):
    """Return number corresponding to excel-style column."""
    number=-25
    for l in c:
    if not l in string.ascii_letters:
    return False
    number+=ord(l.upper())-64+25
    return number


    Code runs:

    >>> column_to_number('2')
    False
    >>> column_to_number('A')
    1
    >>> column_to_number('AB')
    28


    Three letters not working.

    >>> column_to_number('ABA')
    54
    >>> column_to_number('AAB')
    54


    Reference: question answered in C#

    Continue reading...

Compartilhe esta Página