Reputation: 33
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?
Upvotes: 1
Views: 3553
Reputation: 2888
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)
Upvotes: 1
Reputation: 49318
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))
Upvotes: 7