Search code examples
pythoncounterincrementalphanumeric

Incrementing an alphanumeric string in Python


I need to build a function, which gets a alphanumeric string (0, 1, ... , 8, 9, A, B, C, ... , Z), adds 1 and return the string. For example: 02H9Z is given, the function shall return 02HA0.

I found several random alphanumeric string generators online. They work just fine, but do not solve my problem. Then I started to write a function which checks every single char in a for-loop and compares it to 'A', 'B', ... - but I think that's not much efficient.

Can anyone think of a better solution?


Solution

  • That is base 36. Use the built-in int function, and Numpy's numpy.base_repr:

    import numpy
    s = '02H9Z'
    new = int(s, 36) + 1
    print(numpy.base_repr(new, 36))