How to increment alphanumeric number in python?

rajat maan :

I am creating a passkey of 16 alphanumeric characters where I am generating starting 4 digits with A001, A002, A003 till A999. Once it goes till A999, the alphabet will auto increase to B and digits will again start with 001. And the same process will go till Z999. Once the A-Z series will over, then it will start with AA01 and so on. How to do this thing in python? As I am new in python so I tried it on my own and also tried some examples but I am unable to make the increment of characters. Any ideas or thoughts would be greatly appreciated.

Many thanks

rec=0
new_list16 = []
def autoIncrement():
    global rec
    first = 'A'
    i = chr(ord(first))
    new_list16.append(i)

    while True:
        pStart = 1 #adjust start value, if req'd 
        pInterval = 1 #adjust interval value, if req'd
        if (rec == 0):
            rec += pStart
        else:
            rec = rec + pInterval
        return str(rec).zfill(3)
#print(autoIncrement())
new_list16.append(autoIncrement())

print(*new_list16, sep = '')
tobias_k :

Going from A999 to B001 instead of B000 really messes things up a bit, but you can still use this for the A-Z part, and a simple modulo operation for the numbers.

def excel_format(num):
    # see https://stackoverflow.com/a/182924/1639625
    res = ""
    while num:
        mod = (num - 1) % 26
        res = chr(65 + mod) + res
        num = (num - mod) // 26
    return res

def full_format(num, d=3):
    chars = num // (10**d-1) + 1 # this becomes   A..ZZZ
    digit = num %  (10**d-1) + 1 # this becomes 001..999
    return excel_format(chars) + "{:0{}d}".format(digit, d)

for i in range(10000):
    print(i, full_format(i, d=2))

Number of digits in the numeric part is controlled with the optional d parameter. I'll use 2 for purpose of demonstration, but 3 works just as well.

0 A01
...
98 A99
99 B01
...
2573 Z99
2574 AA01
...
9998 CW99
9999 CX01

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=11624&siteId=1