1

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?

  • 1
    I would think it as hexadecimal(Or whatever base) rather than trying and increasing a string. – Rockybilly Dec 15 '16 at 08:29
  • So you want to do calculation using bas 36? –  Dec 15 '16 at 08:32
  • Possible duplicate of [How to convert an integer in any base to a string?](http://stackoverflow.com/questions/2267362/how-to-convert-an-integer-in-any-base-to-a-string) –  Dec 15 '16 at 08:33

2 Answers2

7

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))
TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97
1

Here's the solution using only built-in functions:

l = '0123456789abcdefghijklmnopqrstuvwxyz'

def increase(s):
    new_s = []
    continue_change = True
    for c in s[::-1].lower():
        if continue_change:
            if c == 'z':
                new_s.insert(0, '0')
            else:
                new_s.insert(0, l[l.index(c) + 1])
                continue_change = False
        else:
            new_s.insert(0, c)

    return ''.join(new_s)
Fejs
  • 2,734
  • 3
  • 21
  • 40