pythonchrord

Alphabetic increment pattern in python - a-z, aa-az,ba-bz…aaa-azz


I am trying to work out how to achieve an alphabetic increment that is ran over many items as part of a renamer.

I am using chr() and ord() to retrieve the next letter increment after a starting letter such as:

startletter = 'a'
bb = 0
preletters = ''
pinc = 1
for o in objects:
    newchar = chr(ord(startletter) + bb)
    #rename here such as joining the preletters with the newchar
    bb = bb + 1 

I then check if the newchar was ‘z’ and then if so make the preletter as follows:

if newchar == 'z':
    preletters = chr(pinc)
    pinc = pinc + 1

I am a bit lost to make this more efficient, ideally what I want should produce a pattern such as

a,b,c,d …z for the first 26 items

and then start doubling the letters like this

aa,ab,ac,ad,… az 
ba,bb,bc,… bz

once we hit zz, we’d then need to triple them to:

aaa, aab, aac,…

Any help appreciated.


Solution

  • Not quite sure what you're asking, but far more flexible is get_excel_column_number:

    def get_excel_column_name(column_number):
        result = []
        while column_number > 0:
            modulus = (column_number - 1) % 26
            result.append(chr(modulus + ord('A')))
            column_number = (column_number - modulus) // 26
        return ''.join(reversed(result))
    

    This function lets you know that get_excel_column_number(1) is A and the millionth column is BDWGN, without having to look at all the columns in between.

    (Note that this function uses 1-indexed columns. Add column_number += 1 as the first line if you want 0-indexed columns.)

    And obviously you can create an iterator by:

    def my_iterator():
        for i in itertools.count(1):
            yield get_excel_column_name(i)
    

    I copied the implementation of get_excel_column_name from here and converted it to Python.

    (I just realized you wanted lowercase. Just replace 'A' with 'a')